Simplest way to wait some asynchronous tasks complete, in Javascript?
asynchronous, javascript, mongoose, node.js, synchronous
Solution
I see you are using `mongoose` so you are talking about server-side JavaScript. In that case I advice looking at async module and use `async.parallel(...)`. You will find this module really helpful - it was developed to solve the problem you are struggling with. Your code may look like this
var async = require('async');
var calls = [];
['aaa','bbb','ccc'].forEach(function(name){
calls.push(function(callback) {
conn.collection(name).drop(function(err) {
if (err)
return callback(err);
console.log('dropped');
callback(null, name);
});
}
)});
async.parallel(calls, function(err, result) {
/* this code will run after all calls finished the job or
when any of the calls passes an error */
if (err)
return console.log(err);
console.log(result);
});
Problem
I want to drop some mongodb collections, but that's an asynchronous task. The code will be: ``` var mongoose = require('mongoose'); mongoose.connect('mongo://localhost/xxx'); var conn = mongoose.connection; ['aaa','bbb','ccc'].forEach(function(name){ conn.collection(name).drop(function(err) { console.log('dropped'); }); }); console.log('all dropped'); ``` The console displays: ``` all dropped dropped dropped dropped ``` What is the simplest way to make sure `all dropped` will be printed after all collections has been dropped? Any 3rd-party can be used to simplify the code.