如何等待异步映射函数?



让我快点说重点。我有一个获取用户id的函数。它工作得很好。

const allIds = await fetchAllIds(someUrl);

现在问题来了,当我想做一些不同的事情。我想循环这些id并对它们做一些async await。即主要为每个axios获取一些数据,并进行相应的修改。

allIds.map(async (id) => {
// 1. Fetch some data (try, catch and await)
// 2. Modify the id based on that data
// 3. Return the id, namely replace the old one
});

在我的代码末尾,我只是返回allIds。问题是,它在没有等待map函数完全执行的情况下返回它们。我尝试了不同的方法,但似乎都不起作用。你能帮我使它工作,或者建议一些其他可能的解决方案吗?提前感谢!

你基本上有两个问题:

  1. 您忽略了map
  2. 的返回值
  3. map将返回一个数组的承诺,你没有await他们全部

:

const promises = allIds.map(...);
const replacement_ids = await Promise.all(promises);
return replacement_ids;

用这个代替。

const newList = await Promise.all(allIds.map(id=>new Promise(async(res)=>{
// do your async here and get result;
res(result);
})));

最新更新