node.js - map /加入 Bluebird 和 Mongoose

标签 node.js promise bluebird

我想映射并加入我的 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 组合到一个数组类型对象中。

但是...更改后的对象不会传递,它只会传递原始对象。因此,我必须实现一个在每个“阶段”中更改的全局对象

但是...这也行不通。全局对象始终是 eachmap 之前 .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/

相关文章:

node.js - 无法使用 Lambda 和 API 网关访问 API

node.js - Nodejs中HTTPS请求超时

javascript - 使用 Promise 将错误作为数组对象值返回

javascript - promise 的连接不返回任何内容 (JS)

node.js - 如何在 ReactJS 中显示来自 MongoDB 的图像

node.js - Heroku 为具有不寻常文件夹结构的 Node 应用程序构建

javascript - jQuery Promises 和 Deferred,困惑

javascript - 如何在 Node.js 中实现递归 Promise 调用

node.js - Promise-IO seq,我做错了什么?

node.js - 有前途的多党制