如何控制2个代码块的执行?

时间:2018-09-07 13:06:03

标签: javascript mongoose

resolve(parent, args) {

  let argumentCheck = (args.title && args.content && args.author_id);
  let author_idCheck = false;

  try {
    if(argumentCheck ==  undefined) {
      throw new Error("New article arguments are not defined!");
    }
    else {
      console.log("ArgumentCheck passed!")
    }

    userModel_i.findById(args.author_id, (error, userObject)=>{
      if(userObject !== undefined){
        author_idCheck = true;
        console.log(author_idCheck)
        //If this is placed outside of callback then author_idCheck undefined
        //Because code is asynchornous takes time for callback function run
        //Therefore console.log run before callback finishes hence undefined
      }
    })

    console.log("run")

    let articleModel = new articleModel_i({
      title: args.title,
      content: args.content,
      author_id: args.author_id, //Author ID should come from somewhere in applciation
      createdAt: String(new Date())
    })

    return articleModel.save();

  }
  catch(e) { console.log(e) }

}

我有2个代码块:

  1. findById
  2. 的回调函数中的代码
  3. condole.log("run")之后的代码。

回调函数需要花一些时间才能运行,因此console.log()和之后的代码会先运行。问题是condole.log("run")之后的代码取决于代码块1的回调中的代码,因此应首先运行该回调。我无法将代码放在控制台内的回调中,因为return语句将用于回调而不是resolve函数。

是否有任何方法可以使回调先运行,然后在控制台后运行代码?我在想也许将它们都传递给函数并在其中运行?

1 个答案:

答案 0 :(得分:1)

如果未指定回调,则

findById返回Query。其中有一个then-able方法可返回Promise。因此,您可以重构代码以使用.then查找userModel_i,然后在异步任务之后创建一个articleModel

// return the promise
return userModel_i.findById(args.author_id)
  .then(userObject => {
    if(userObject !== undefined){
      author_idCheck = true;
      console.log(author_idCheck)
    }
    return userObject;
  })
  .then(userObject => {
    // push code block 2 inside the promise resolver 
    console.log("run")

    let articleModel = new articleModel_i({
      title: args.title,
      content: args.content,
      author_id: args.author_id,
      createdAt: String(new Date())
    })

    // return article when resolved
    return articleModel.save();
  });