【发布时间】:2014-07-11 23:11:24
【问题描述】:
我正在使用async 和promise 运行种子脚本,但在所有promses 都是rejected 的情况下,脚本永远不会完成。
因为它是一个播种脚本,它被设置为不播种已经有数据的模型。
这是(删节的)我的代码
知道我错过了什么吗?
seed = function(collectionName, data) {
return new Promise(function(fulfill, reject) {
var collection = collections[collectionName];
collection.find().exec(function(err, found) {
if (found.length > 0) {
console.log("There are", found.length, collectionName, "records in the database already.");
reject();
} else {
collection.createEach(data, function(err, models) {
if (err || _.isUndefined(models)) {
console.log("Could not create", collectionName, "collection!");
reject();
} else {
collection.find().exec(function(err, found) {
fulfill(found);
});
}
});
}
});
});
};
run = function(models, done) {
async.each(models, function(modelName, next) {
seed(modelName, modelData[modelName]).then(function(codes) {
console.log("Seeded", codes.length, modelName, "records.");
next();
}, function(err){
console.log("Seeding of", modelName, "failed", err.stack);
done(err);
});
}, done);
};
run(["widget", "thingo", "dooverlackey"], function(err){
if (err) console.error("Completed with errors", err);
else console.log("Completed without errors");
process.exit();
});
【问题讨论】:
-
此外,如果我将错误消息传递给
reject("my error"),那么整个过程都会在第一个错误处停止,这也不是我想要的。我只是希望它跳过任何已经有数据的模型。 -
Promises 已经提供了异步聚合和结构化。真的没有理由在这里使用异步模块。您可以简单地
.then在 for 循环中链接它们而无需异步。 -
谢谢 Benjamin - 这是一个很好的观点,但是使用
async我可以将另一个模型添加到我的数组中,瞧。也许摆脱 Promise 结构反而会简化事情。 -
你可以 .then 用 promises 得到同样的中提琴
标签: javascript node.js asynchronous promise