我想删除一些mongodb集合,但这是一个异步任务。代码将是:
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');
控制台显示:
all dropped dropped dropped dropped
确保all dropped删除所有收藏集后将被打印的最简单方法是什么?任何第三方都可以用来简化代码。
all dropped
我看到您正在使用,mongoose因此您正在谈论服务器端JavaScript。在这种情况下,我建议您查看异步模块并使用async.parallel(...)。您会发现此模块确实有用-它是为解决您所遇到的问题而开发的。您的代码可能如下所示
mongoose
async.parallel(...)
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); });