gpt4 book ai didi

node.js - 使用 q.map 时如何避免破坏 promise 链?

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:26 25 4
gpt4 key购买 nike

我想我可能太喜欢 promise 了。我有一组鹅,在返回最终值之前我想执行任意数量的操作。我发现在第一个 return 语句之后,链条就断了。如果我的集合有 10 个项目,则恰好有 10 个项目将被放置在数据库中,但是当我尝试从下面的“return Q.all(promises)”语句构建 API 响应时,我得到空值。

为了进行测试,我将 console.log 语句放入一个在第一个语句之后触发的 Promise 中,并将 console.log 放入我的expressjs 路由中,该路由需要有关鹅的详细信息。 API 响应总是首先完成“[null, null]”,然后最终我得到链中第二个和第三个 promise 的条目。

我是如何创建这种竞争条件的以及如何修复它?

var promises = geese.map(function(goose) {
determineGooseType(goose.details)
.then(function(type) {
return recordNewGooseType(type)
})
.then(function(dbInsertResult) {
we never really got here!
})
.catch(function(err) {
log some stuff
});
}

return Q.all(promises);

最佳答案

您没有 promise 数组,而是有一个未定义值数组(并且Q.all没有警告您):您的映射器函数没有返回任何内容。您缺少 return 语句:

var promises = geese.map(function(goose) {
return determineGooseType(goose.details)
//^^^^^^
.then(function(type) {
return recordNewGooseType(type)
})
.then(function(dbInsertResult) {
// now getting here before resolving the .all() promise!
})
.catch(function(err) {
log some stuff
});
}
return Q.all(promises);

关于node.js - 使用 q.map 时如何避免破坏 promise 链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28298262/

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