Search code examples
javascriptasynchronouscallbackbluebird

for loop exit before callback is finished


I have a for loop which is calling an async function. I need this function to then call a callback at the end of the for loop but only when all my async functions have returned their result. I have tried this:

for(var i = 0; i < vaccinsCount; i++){
    getVaccinAddress(i, address, provider, function(result){
       if(result.success){
         console.log("result:" + result.values);
         vaccines.push(result.values);
       } else {
         callback({success: false, message: result.message}); 
       }
   });
}
callback({success: true, values: vaccines}); 

instead what is happening is that the code enters the for loop then call then async function then exits straigh away. How could i get around this ?

getVaccinAddress is the Async Function that does a server call.

EDIT

I am using NodeJS, therefore the solution is to then use bluebird, I however have no idea on how to implement this with bluebird.


Solution

  • You can call callback() when vaccines.length is equal to vaccinsCount

    for(var i = 0; i < vaccinsCount; i++) {
      (function(i) {
        getVaccinAddress(i, address, provider, function(result) {
           if(result.success) {
             console.log("result:" + result.values);
             vaccines.push(result.values);
             if (vaccines.length === vaccinsCount) {
                // call `callback()` here
             }            
           }
        });
      })(i);
    }