我想映射并加入我的 Mongoose 模型,例如:
MyModel.myPromisifiedMethod parameter, (err,res) ->
.then((res) ->
# do stuff to res
)
.then((res) ->
Promise.map res, ((eachItem) ->
# do stuff to to eachItem
AnotherModel.get parameter, (err,res) ->
# do stuff with res and eachItem
)
join eachItem, ((eachItem) ->
console.log eachItem
)
)
.then((finalResult) ->
res.status(202).send
result:finalResult
)
map 是一个迭代器,我需要它,因为我对 Mongo 的请求有 50000 个文档长。然而上面不起作用,特别是连接部分。我在网上找不到任何例子。感谢帮助。
这就是我进一步工作的方式,包含以下答案:
MyModel.myPromisifiedMethod parameter, (err,res) ->
.then((res) ->
Promise.all res.map (eachItem) ->
# do stuff to to eachItem
AnotherModel.get parameter, (err,res) ->
# do stuff with res and eachItem
)
.map((res) ->
# do stuff with res
)
.each((res) ->
# do stuff with res
.then((finalResult) ->
res.status(202).send
result:finalResult
)
“第二个”.map
看起来多余,但它有效。 .each
的工作方式很有趣,就像一个reduce,至少我是从 Apache Spark 了解到的。 each
将映射的和已完成的 Promise 组合到一个数组类型对象中。
但是...更改后的对象不会传递,它只会传递原始对象。因此,我必须实现一个在每个“阶段”中更改的全局对象。
但是...这也行不通。全局对象始终是 each
或 map
之前 .then
的最后一个值。
本质上我仍然不知道如何让它发挥作用。
最佳答案
我能想到的一种方法是使用 Promise.all:
function mapReduce(inputs, mapFn, reduceFn){
return Promise.all(inputs.map(mapFn)).then(reduceFn);
}
你的代码会变成这样:
MyModel.myPromisifiedMethod parameter, (err,res) ->
.then((res) ->
# do stuff to res
)
.then((res) ->
Promise.all res.map (eachItem) ->
# do stuff to to eachItem
AnotherModel.get parameter, (err,res) ->
# do stuff with res and eachItem
)
.then((res) ->
res.reduce (sumdValue, eachItem) ->
# do stuff to to eachItem
eachItem + sumValue
)
.then((finalResult) ->
res.status(202).send
result:finalResult
)
关于node.js - map /加入 Bluebird 和 Mongoose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32928325/