讓我快速進入正題。我有一個獲取一些用戶 ID 的函式。它作業得很好。
const allIds = await fetchAllIds(someUrl);
現在,當我想做一些不同的事情時,問題就來了。我想遍歷這些 id 并用它們做一些異步等待的東西。也就是主要用 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 函式完全執行的情況下回傳它們。我嘗試了不同的方法,但似乎都沒有奏效。你能幫我讓它作業還是建議一些其他可能的解決方案?提前致謝!
uj5u.com熱心網友回復:
你基本上有兩個問題:
- 您忽略了的回傳值
map - 將
map回傳一個 Promises 陣列,而您并沒有await全部使用它們
所以:
const promises = allIds.map(...);
const replacement_ids = await Promise.all(promises);
return replacement_ids;
uj5u.com熱心網友回復:
改用這個。
const newList = await Promise.all(allIds.map(id=>new Promise(async(res)=>{
// do your async here and get result;
res(result);
})));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/480676.html
標籤:javascript 异步 异步等待 axios 切里奥
