在继续之前等待回调函数完成

时间:2016-01-26 15:41:46

标签: javascript node.js callback

function main(cb) {

  getFirstData(function(ResultsForFirstQuery) {

    // Do something with ResultsForFirstQuery

    // Call getSecondData with param Id I get from ResultsForFirstQuery()
    getSecondData(function(ResultsForFirstQuery[0].Id)) {

      // Now here I need to do something with data data I get from getSeconData(),
      // But the program only calls this AFTER cb(result) in MAIN because of async?
      // How to make the program to wait for this function to finish?

    });

  });

  // THIS GETS CALLED BEFORE getSeconData() is finished
  // but I need to modify data i get from getSeconData before
  // calling this.
  cb(result);
}

funtion getFirstData(cb) {

  var rows;
  var sql = "sql magic here"

  /* Make Sql-query here and return results as rows in cb */

  cb(rows);

}

funtion getSecondData(id, cb) {

  var rows;
  var sql = "sql magic here"

  /* Make Sql-query here and return its results as rows in cb */

  cb(rows);

}

我尝试对代码进行评论,以便SO读者可以更好地理解问题。函数main(cb)是从另一个文件中调用的,我使用它的回调来发送邮件,但是我把它从代码中删除了,因为我认为它不相关。我还省略了代码块中的函数所做的代码,因为我认为它不相关,但如果有人感兴趣它们是用于从多个数据库表生成XML文件。这也是node.js应用程序。

我遇到的问题是,当我调用getFirstData()和getSecondData()并获得结果时,getSeconData()在getFirstData()结束之前不会执行,并且会生成这两个函数的结果。如何修改此程序以使其在继续之前等待getSeconData()完成?

2 个答案:

答案 0 :(得分:2)

如评论中所述,您需要在第二个函数的回调中调用cb(result)

function main(cb) {

  getFirstData(function(ResultsForFirstQuery) {
    getSecondData(ResultsForFirstQuery[0].Id, function(ResultsForSecondQuery) {
      // compute away...
      cb(result);
    });
  });

}

答案 1 :(得分:0)

这样做的好方法是通过Promises。

var a = getFirstData(cb) {
    return new Promise( function( resolve, reject ){
         // your code here
         resolve( some data );
    });
}
var b = getSecondData(id, cb) {
    return new Promise( function( resolve, reject ){
         // your code here
         resolve( some data );
    });
}

Promise.all( a, b).then(function(){
    // once both promises resolve, continue
});