Home > Back-end >  aysnc map is returning empty array
aysnc map is returning empty array

Time:09-27

the following code block is returning an empty array but if I use for loop instead it works fine

let allMenus = [];
foodMenu = foodMenu.map(async menu => allMenus.push(await handleMenu(menu, DBName)))
console.log(foodMenu); // returns empty array

this return the data perfectly but I want to use map

let allMenus = [];
     for (const menu in foodMenu) { 
       allMenus.push(await handleMenu(foodMenu[menu], DBName)); // this returns the data
     }

CodePudding user response:

A few things:

Firstly, Array#map expects a return value because it generates a new array. While your code works, it is not the intent of the method.

Using await in an array enumerator callback (Array#map, in yours case) will defer the execution, but it does not pause between callbacks. That means the code will be run, but it will not be resolved in sequence in the way you are expecting.

Do this:

let foodMenu = foodMenu.map(async menu => {
  const newMenuItem = await handleMenu(menu, DBName)
  console.log(newMenuItem)
  allMenus.push(menu)
})

You will find that your return value, the empty array, will be printed first, and then your new menus printed afterwards. It is out of order

To resolve this, you either need to

  1. Make it a loop, where await that will pause in the way you expect or
  2. Map the promises into an array and wait for them all to finish, using Promise.all
let foodMenu =  await Promise.all(foodMenu.map(menu => handleMenu(menu, DBName)))
  • Related