-1

I have a problem with a closure in my loop. Here what I do :

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 );
   }
});

So I want to execute my function addUsersScore() with variable usersScoreByLigue updated by precedent function calcUsersScore(); .

My problem is that this function calcUsersScore() is long to execute (some requests with database and multiple tests) so how to wait for it and sure that addUsersScore() fire after ?

Thanks in advance,

t.niese
  • 39,256
  • 9
  • 74
  • 101
chles
  • 175
  • 1
  • 1
  • 11
  • 1
    add a callback parameter in your `that.calcUsersScore( that.usersScoresByLigue,cyclist,bonus, callback )` and pass `addUserScore ` as parameter and just fire the callback aa last like `callback()` – ricky Jun 30 '17 at 09:21
  • 2
    Possible duplicate of [make async call inside forEach](https://stackoverflow.com/questions/29178868/make-async-call-inside-foreach) – t.niese Jun 30 '17 at 09:22
  • I would go with Promises and use a library like [bluebirdjs](http://bluebirdjs.com/docs/getting-started.html) – t.niese Jun 30 '17 at 09:23

1 Answers1

0

If you can modify the code for that.calcUsersScore, you can make it use a callBack after it finishes the other stuff:

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();
     }
   } 
}

and you code can become:

 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 );
       }
    });
 });
bluehipy
  • 2,254
  • 1
  • 13
  • 19