Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

aysnc map is returning empty array

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
     }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading