Skip to content

Instantly share code, notes, and snippets.

@ycmjason
Created May 30, 2017 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ycmjason/44b5a5bbf79dc0fb4f6684aa615653ad to your computer and use it in GitHub Desktop.
Save ycmjason/44b5a5bbf79dc0fb4f6684aa615653ad to your computer and use it in GitHub Desktop.
Ensure multiple asynchronous call finishes before executing the callback
function wait(n, cb){
if(n <= 0) cb();
let aggregated_result = {};
let count = 0;
return function done(res){
Object.assign(aggregated_result, res);
if(++count === n) cb(aggregated_result);
}
}
// Usage:
var done = wait(3, function(){
console.log("Here the three async functions are done");
});
doAsync(done);
doAsync2(done);
doAsync3(done);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment