在 Javascript 中等待一些异步任务完成的最简单方法? [英] Simplest way to wait some asynchronous tasks complete, in Javascript?
问题描述
我想删除一些 mongodb 集合,但这是一个异步任务.代码将是:
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');
控制台显示:
all dropped
dropped
dropped
dropped
确保在删除所有集合后打印 all drop
的最简单方法是什么?任何第三方都可以用来简化代码.
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.
推荐答案
我看到你在使用 mongoose
所以你在谈论服务器端 JavaScript.在这种情况下,我建议查看 async 模块 并使用 async.parallel(...)代码>.你会发现这个模块真的很有帮助——它是为了解决你正在努力解决的问题而开发的.您的代码可能如下所示
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);
});
这篇关于在 Javascript 中等待一些异步任务完成的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!