aysnc映射返回空数组



下面的代码块返回一个空数组,但如果我使用for循环,它可以很好地进行

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

这可以完美地返回数据,但我想使用地图

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

几件事:

首先,Array#map期望return值,因为它生成了一个新数组。虽然您的代码可以工作,但这不是该方法的意图。

在数组枚举器回调中使用await(在您的情况下为Array#map(将推迟执行,但不会在回调之间暂停。这意味着代码将运行,但不会按照您期望的方式按顺序解析。

这样做:

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

您会发现您的返回值,即空数组,将首先打印,然后打印新菜单。出现故障

要解决此问题,您要么需要

  1. 使其成为一个循环,其中await将以您期望的方式暂停或
  2. 使用Promise.all将promise映射到一个数组中,并等待它们全部完成
let foodMenu =  await Promise.all(foodMenu.map(menu => handleMenu(menu, DBName)))

最新更新