【问题标题】:How can I make queries inside a map function async? - Mongoose如何在地图函数中进行异步查询? - 猫鼬
【发布时间】:2021-08-16 14:06:40
【问题描述】:

所以我需要使用 .map 函数进行查询,然后将其推送到一个数组并返回它,但问题是数组在返回时总是空的,因为它不是异步的,我试过 async/await 但这不是工作。我的代码示例如下:

let arrayToSend = []

anotherArray.map(obj => {
    Model.findOne({_id: id}).exec(function(err, result){
        if (!err) {
           arrayToSend.push(result) 
        } else {
           let anotherObj = {key: value}
           arrayToSend.push(anotherObj) 
        }
    })
}

return res.json({arrayToSend})

【问题讨论】:

  • map 中使用async/await 时还需要Promise.all

标签: javascript node.js express mongoose


【解决方案1】:

你可以使用 for...of 循环而不是使用 async/await 语法的 map

let arrayToSend = []

for(const obj of anotherArray) {
    try {
       const result = await Model.findOne({_id: id}).exec()
       arrayToSend.push(result) 
   catch (err) {
       let anotherObj = {key: value}
       arrayToSend.push(anotherObj) 
   }
}

return res.json({arrayToSend})

【讨论】:

  • 这不起作用。数组还是空的。
  • 这应该根据这个文档工作masteringjs.io/tutorials/mongoose/promise你能分享更多你的代码吗,比如函数声明或anotherArray init?
  • 我得到的代码与其他一些更改一起工作!非常感谢您尝试帮助我。
  • for 使调用同步LOOK AT THIS ANSWER
猜你喜欢
  • 1970-01-01
  • 2023-04-08
  • 2020-09-12
  • 2016-04-07
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 2018-02-27
相关资源
最近更新 更多