【问题标题】:Asynchronous function in loop forEach循环 forEach 中的异步函数
【发布时间】:2017-06-30 09:14:24
【问题描述】:

我的循环中的 闭包 有问题。这是我的工作:

this.newResults.cyclists.forEach(function(cyclist){
   that.calcUsersScore( that.usersScoresByLigue,cyclist,bonus );

   bonus--;

   if(bonus === 0) {
      console.log("c'est terminé");
      that.addUsersScore( that.usersScoresByLigue );
   }
});

所以我想执行我的函数addUsersScore(),变量usersScoreByLigue由先例函数calcUsersScore();更新。

我的问题是这个函数calcUsersScore() 执行时间很长(一些带有数据库和多个测试的请求)所以如何等待它并确保addUsersScore() 在之后触发?

提前致谢,

【问题讨论】:

  • that.calcUsersScore( that.usersScoresByLigue,cyclist,bonus, callback ) 中添加一个回调参数并将addUserScore 作为参数传递,最后像callback() 一样触发回调aa
  • 我会选择 Promises 并使用像 bluebirdjs 这样的库

标签: javascript loops asynchronous


【解决方案1】:

如果你可以修改that.calcUsersScore的代码,你可以让它在完成其他工作后使用callBack:

calcUsersScore: function( usersScoresByLigue, cyclist, bonus, callback) {
  //do whatever it does allready
  // on handler of the server response call the callback
  xhr.onreadystatechange = function() {
     if(xhr.readyState == 4 && xhr.status == 200) {
        callback && callback();
     }
   } 
}

你的代码可以变成:

 this.newResults.cyclists.forEach(function(cyclist){
    that.calcUsersScore( that.usersScoresByLigue, cyclist, bonus, function(){
       bonus--;
       if(bonus === 0) {
         console.log("c'est terminé");
        that.addUsersScore( that.usersScoresByLigue );
       }
    });
 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    相关资源
    最近更新 更多