node.js - Mongoose eachAsync:承诺的执行顺序出乎意料
问题描述
我正在使用库 mongoose 5.4.20、request 2.88.0、q 1.5.1 和 deasync 0.1.14。
当使用 .cursor() 和 .eachAsync() 时,promise 不会按照我期望的顺序得到解决。特别是,我向数据库发出请求,并且对于每个返回的文档,我通过异步序列发出几个外部请求。示例代码如下:
请求承诺:
function Request (options) {
const result = Q.defer();
request(options, function (error, response, body) {
if (error) {
result.reject(error);
} else {
result.resolve(body);
}
});
return result.promise;
}
异步系列承诺:
function Series (entry) {
const result = Q.defer();
const errors = [];
//Iterate over some given array
async.eachSeries(array, function (doc, cb) {
//Make some async request
return Request(doc)
.then(function (body) {
//do stuff with 'body' and 'entry'
})
.then(function () {
//Move to the next doc in 'array'
return cb(null);
})
.fail(function (err) {
//Handle errors
errors.push(err);
//Move to the next doc in 'array'
return cb(null);
});
}, function (err, results) {
if (err) {
errors.push(err);
}
if (errors.length !== 0) {
result.reject(errors);
} else {
console.log('A');
result.resolve();
}
});
return result.promise;
}
猫鼬:
mongooseModel
.find()
.cursor()
.eachAsync(entry => Series(entry))
.then(function () {
console.log('B');
}, function (err) {
console.log(err);
});
让我感到困惑的是,在 .eachAsync() 之后的 .then() 中的最终回调似乎在 .eachAsync() 中的承诺解决之前被调用,即在 'console.log('B')' 之前调用'console.log('B')'。日志('A')'。我原以为 .eachAsync() 将等到 promise 被解决,然后从集合中提取下一个文档,依此类推,只有在最后,当所有 promise 都解决时,最终的 .then() 是叫。
任何关于我做错了什么的建议将不胜感激。谢谢。
解决方案
推荐阅读
- javascript - 如何在您的谷歌搜索上覆盖 iframe?
- unity3d - Hololens 具有空间意识的角色
- c# - 如何在 C# 中找到 wsdl 服务的参数
- apache-kafka - Apache Kafka 分区偏移量在重新平衡期间倒带
- r - 绘制澳大利亚各州的叶绿素图
- python - youtube 数据 api 将哪些内容归类为无效关键字?
- typescript - TypeScript 导入:无法加载资源 (404)
- r - 将除第一个字母之外的句子的每个单词大写
- php - 将 WooCommerce 城市字段更改为前端和管理中的下拉列表
- swift - macOS WidgetKit 扩展中的钥匙串错误 -25308 (errSecInteractionNotAllowed)