0

So I need to make queries using a .map function and then push it to an array and return it but the problem is the array is always empty when returning because its not async, I have tried async/await but that does not work. An example of my code would be like this:

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})
SnaccOvenFlour
  • 158
  • 3
  • 14

1 Answers1

0

You could use the for…of loop instead of map with the async/await syntax

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})
WEBjuju
  • 5,797
  • 4
  • 27
  • 36
gladix
  • 302
  • 2
  • 11
  • This does not work. The array is still empty. – SnaccOvenFlour Aug 16 '21 at 16:27
  • This should be working according to this documenttion https://masteringjs.io/tutorials/mongoose/promise Could you share a little bit more of your code, like the function declaration or the anotherArray init ? – gladix Aug 17 '21 at 08:13
  • I got the code working with some other changes! Thanks so much for trying to help me. – SnaccOvenFlour Aug 17 '21 at 09:29
  • `for` makes the calls *synchronous*. [LOOK AT THIS ANSWER](https://stackoverflow.com/questions/40140149/use-async-await-with-array-map#answer-59471024) – WEBjuju Jan 22 '22 at 02:04