我想讓地圖異步運行。我嘗試使用 async 和 Promise.all 但我不確定我哪里出錯了。這是我寫的代碼
// this is the id => [1,2,3] and total of each => [2, 3, 2]
useEffect(()=> {
countNumFunc(idList)
})
const countNumFunc = (idlist) => {
let count = 0
Promise.all(idList.map(async (id) => {
console.log("id = ", id)
getInfoFromDb(id).then((res) => {
if(res.data) {
count = count res.data.total
console.log("Count = ", res.data.total)
}
}).catch(error => {
console.log("error = ", error)
})
}))
console.log("Count total = ", count)
}
這里的輸出應該是:
id = 1
Count = 2
id = 2
Count = 5
id = 3
Count = 7
Count total = 7
但輸出是:
id = 1
id = 2
id = 3
Count total = 0
Count = 2
Count = 3
Count = 2
uj5u.com熱心網友回復:
要獲得所需的結果,您應該:
不使用
Promise.all
:Promise.all
是當您想先創建所有承諾然后等待它們時。但是從您想要的輸出中,它顯示您想要一個一個地創建承諾(執行資料庫查詢),每次都等待前一個解決。不使用
.map()
。首先,.map()
回傳一個陣列。如果您對該陣列沒有用處,請不要使用.map()
. 其次,.map()
將同步進行所有迭代 - 進行回呼沒有幫助async
。
而是宣告countNumFunc
為異步函式,使用 回圈for..of
,以及將決議為await
的值。getInfoFromDb(id)
其次,你似乎想顯示一個運行計數,所以你不應該顯示res.data.total
,而只是count
:
// Mock:
const getInfoFromDb = async (i) => ({ data: {total: [0, 2, 3, 2][i]} });
const countNumFunc = async (idList) => {
let count = 0
for (let id of idList) {
console.log("id = ", id)
const res = await getInfoFromDb(id);
if(res.data) {
count = count res.data.total
console.log("Count = ", count)
}
}
console.log("Count total = ", count)
}
countNumFunc([1,2,3])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/508489.html
標籤:javascript 节点.js 反应 异步 承诺