首页 > 解决方案 > 异步等待不等待

问题描述

我希望我的代码等待并让jsonObj.forEach...通过 2 个 mongodb 查询,然后转到下一个(console.log(branch))。为此,我使用 async/await 但即使在那之后我也没有得到所需的结果,因为课程和分支数组打印为空。

jsonObj.forEach(async(data)=>{

  try {
    var result = await collections.collection('studentData').find({rollNumber:parseInt(data.rollNumber)}).toArray()
    console.log('--------data---------')
    if (result[0]) {
      course.push(result[0].course)
      branch.push(result[0].branch)
      console.log('-------- entry object ----------')
      await collections.collection('something').insertOne(something,(err,res)=>{if (err){console.log(err)}else {console.log('inserted')}})
    } else {
      console.log('not inserted')
    }
  } catch (e) {
    console.log(e)
  }
}
)

var title = 'Result is out'
var body = 'Result of' + reqs.body.company
console.log('-------------branch and course--------------')
console.log(branch)
console.log(course)

知道有什么问题吗?以及如何获得所需的结果。

标签: javascript

解决方案


您将需要返回一个 Promise。

(data, callback)

然后处理回调。

我强烈推荐使用这个库:

https://caolan.github.io/async/docs.html


推荐阅读