Javascript 等待Promise.all中的array.map迭代

Javascript 等待Promise.all中的array.map迭代,javascript,node.js,asynchronous,promise,Javascript,Node.js,Asynchronous,Promise,我有下面的代码,如果客户不存在,应该为他们添加项目。执行应该是并行的 await Promise.all( customers.map(async (customer) => { return customer.items.map(async (item) => { return new Promise(async (resolve) => { const productExists = someA

我有下面的代码,如果客户不存在,应该为他们添加项目。执行应该是并行的

await Promise.all(
    customers.map(async (customer) => {
        return customer.items.map(async (item) => {
            return new Promise(async (resolve) => {
                const productExists = someArray.some(
                    (arrayValue) => arrayValue === item.id
                );
                if (!productExists) {
                    logger.info(
                    `customer item ${item.id} does not exist, creating...`
                    );
                    await createCustomerItem(item.id);
                    logger.info(`customer item ${item.id} created.`);

                    someArray.push(item.id);
                } else {
                    logger.info(`customer item ${item.id} already exists, skipping...`);
                }
                resolve(true);
            });
        });
    })

);

logger.info(`All items should now be present`);
问题是在
的情况下,执行没有等待
createCustomerItem
解决!产品存在)

这是日志

customer item 32310 does not exist, creating...
customer item ao does not exist, creating...
customer item ute does not exist, creating...
All items should not be present
customer item ao created.
customer item ute created.
customer item 32310 created.
当然,
所有项目都不应该出现
应该排在最后

当所有项目都已存在时,流程看起来不错。

请尝试:

它不会返回承诺数组,而是将内容扁平化为一个简单的承诺数组,这是
Promise.all
所期望的


注意:从您的问题来看,是否需要保存每个客户的项目分组并不明显。如果是,请注意,此解决方案将数据结构更改为扁平列表,因此您将丢失分组。在你的
项目中添加一些
customerId
,或者在评论中尝试@blex的建议。

你可以这样做

const fruitsToGet = ['apple', 'grape', 'pear']

const mapLoop = async () => {
  console.log('Start')

  const promises = await fruitsToGet.map(async fruit => {
    const numFruit = new Promise((resolve, reject) => {
      setTimeout(() => resolve(fruit), 1000)
    });
    return numFruit
  })
  const numFruits = await Promise.all(promises)
  console.log(numFruits)

  console.log('End')
}

mapLoop();
结果

Start
["apple", "grape", "pear"]
End

map
对承诺一无所知,。不幸的是,你不能这样使用map。我认为这是因为Promise.all需要一个承诺数组,而你正在传递一个承诺数组。试试平面地图吧。我想@JulienD在评论中提到的东西会解决你的问题。。。。或者只需将
return customer.items.map()
替换为
return Promise.all(customer.items.map())
Start
["apple", "grape", "pear"]
End