解決forEach函數中異步調用及Promise.all()的基礎使用


上代碼

const arr = [1,2,3,4,5]
function t(num) {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            console.log('定時器', num)
            resolve()
        }, 1000)
    })
}

目前需求。想先forEach執行完畢之后再打印end

arr.forEach(async (i) =>{
    await t(1)
})
console.log('end')

測試發現是先打印end再執行forEach里面的async await

(打印結果)

 

 

 查閱資料(百度)后發現forEach里面是異步執行。所以在怎么用async await也無法按照預期執行

因為forEach是異步,那就把forEach改成for in

for(let i in arr){
    await t(i)
}
console.log('end')

(打印結果 耗時5s)

 

 

 需求處理ok了。再到性能優化環節

因為for里面用await的會先執行完畢再走循環,因此會串行執行接口

就好比如我這里每個請求耗時1s。加起來走完請求就5s了,在用戶體驗上很不友好。

這個時候就需要用到Promise.all()+map()了。  Promise.all()是啥自行查閱資料!

await Promise.all(arr.map(async i=> await t(i)))
console.log('end')

(打印結果 耗時1s)

 

 

 

 需求解決


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM