猿问

用JavaScript等待一些异步任务完成的最简单方法?

我想删除一些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删除所有收藏集后将被打印的最简单方法是什么?任何第三方都可以用来简化代码。


守着星空守着你
浏览 1535回答 3
3回答

米琪卡哇伊

我看到您正在使用,mongoose因此您正在谈论服务器端JavaScript。在这种情况下,我建议您查看异步模块并使用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);});

梦里花落0921

使用承诺。var mongoose = require('mongoose');mongoose.connect('your MongoDB connection string');var conn = mongoose.connection;var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {  return new Promise(function(resolve, reject) {    var collection = conn.collection(name);    collection.drop(function(err) {      if (err) { return reject(err); }      console.log('dropped ' + name);      resolve();    });  });});Promise.all(promises).then(function() { console.log('all dropped)'); }).catch(console.error);这将丢弃每个集合,在每个集合之后打印“已删除”,然后在完成时打印“全部删除”。如果发生错误,则显示为stderr。先前的答案(这早于Node对Promises的本地支持):使用Q承诺或Bluebird承诺。与Q:var Q = require('q');var mongoose = require('mongoose');mongoose.connect('your MongoDB connection string');var conn = mongoose.connection;var promises = ['aaa','bbb','ccc'].map(function(name){    var collection = conn.collection(name);    return Q.ninvoke(collection, 'drop')      .then(function() { console.log('dropped ' + name); });});Q.all(promises).then(function() { console.log('all dropped'); }).fail(console.error);与蓝鸟:var Promise = require('bluebird');var mongoose = Promise.promisifyAll(require('mongoose'));mongoose.connect('your MongoDB connection string');var conn = mongoose.connection;var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {  return conn.collection(name).dropAsync().then(function() {    console.log('dropped ' + name);  });});Promise.all(promises).then(function() { console.log('all dropped'); }).error(console.error);
随时随地看视频慕课网APP
我要回答