【问题标题】:Waiting for callback functions to finish before continuing等待回调函数完成后再继续
【发布时间】:2016-01-26 15:41:46
【问题描述】:
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() 并获取它们的结果时,在 getFirstData() 结束之前不会执行 getSeconData() 并生成这两个函数的结果。如何修改此程序以使其等待 getSeconData() 完成后再继续?

【问题讨论】:

  • 你需要把cb(result) 里面 getSecondData的回调。附言function(ResultsForFirstQuery[0].Id) 语法无效。

标签: javascript node.js callback


【解决方案1】:

评论中提到,需要在第二个函数的回调中调用cb(result)

function main(cb) {

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

}

【讨论】:

    【解决方案2】:

    一个很好的方法是通过 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
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-25
      • 2019-11-01
      • 2021-05-06
      • 2021-05-21
      • 2015-10-03
      • 2013-11-25
      相关资源
      最近更新 更多