0

I want my code to wait and let jsonObj.forEach... to go through 2 mongodb queries and then go to next (console.log(branch)). For this I use async/await but even after that I dont get the required results as course and branch array is printing out to be empty.

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)

Any idea what is wrong? and how can i get the required result.

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
Rajan Lagah
  • 2,373
  • 1
  • 24
  • 40

1 Answers1

0

You will need to have a Promise returning.

(data, callback)

Then handle the callback.

I highly recommend using this library:

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