2021年6月9日 星期三

非同步處理 async await array

 故事是這樣的,有很多小錢包需要分別打 API 去取得餘額,GraphQL API 本身是非同步的,可是當我要加總所有錢包的餘額就會:

const total = async () => {

const walletList = [ a , b , c , d , e]

let total = 0

await walletList.forEach( async  (item,index) => {

    const cash = await getCashApi(item)

     total = total += cash

     console.log(index)

})

console.log(total)

}

然後 index 亂跳 total = 0,完全沒用。


原因是 await 只看後面回傳的是不是 Promise ,但在改寫之前還要釐清是否有順序問題,如果要照順序,就用 reduce 的方法寫,不過我只要算加總,錢包 API 的錢回來的順序不重要,因此可以用 Promise.all 改寫:

const total = async () => {

const walletList = [ a , b , c , d , e]

let total = 0

await Promise.all(walletList.map( async  (item,index) => {

    const cash = await getCashApi(item)

    const outputCash = cash === undefined ?  0  :  cash   //後來發現 API 會回傳 undefined 導致加不起來

     total = total += outputCash

     console.log(index)

}))

console.log(total)

}

這樣就會出來正確的 total 啦



參考資料:







沒有留言:

張貼留言