0

im writing a route to try and return 5 random files with a for loop.. I cant seem to get arr.push(file) to work sync. Any ideas?

router.get('/test',  async (req, res) => {
  let amountOfFiles = 5;
  let arr = []
 for( let i =0; i < amountOfFiles; i++){ 
  let num = Math.floor(Math.random() * 100)
  await gfs.files.findOne({filename: `${num.toString()}.mp3` }, async (err, file) => {
    if(!file){
      return    res.json({
              err: 'upload'
          })
      }
     // console.log(file)
      arr.push(file)
     
  }) 
} 
//console.log(gfs.files.find())
console.log(arr)
 return res.json(arr)

})
  • 1
    check this out https://stackoverflow.com/questions/44813401/passing-in-async-functions-to-node-js-express-js-router – Madhu Nair Apr 26 '21 at 14:04
  • if you do with `promise.all(arr.map()) ` instead of `for and await`. you get better and received final single result array . [Check out](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – prasanth Apr 26 '21 at 14:07
  • Where would promise.all go – joshblitstein Apr 26 '21 at 14:12
  • instead `for` use `array.map` and wrap with [`promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all). After all map async operation finished promise will return the result array to variable . – prasanth Apr 26 '21 at 14:15

0 Answers0