gpt4 book ai didi

javascript - 在Javascript中等待一些异步任务完成的最简单方法?

转载 作者:IT老高 更新时间:2023-10-28 21:47:11 26 4
gpt4 key购买 nike

我想删除一些 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 的最简单方法是什么?任何 3rd-party 都可以用来简化代码。

最佳答案

使用 Promises .

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);

这会丢弃每个集合,在每个集合之后打印“dropped”,然后在完成时打印“all dropped”。如果发生错误,则显示到 stderr


上一个答案(这早于 Node 对 Promises 的原生支持):

使用 Q promise 或 Bluebird promise 。

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);

bluebird :

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);

关于javascript - 在Javascript中等待一些异步任务完成的最简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10551499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com