趟過的一個坑:Array.forEach與 async await一起使用,并沒有達到自己預期的效果,后面查詢資料得知:forEach的第一個參數回調函數并沒有對promise對象做任何處理,導致結果出現異常,我們可以用for ..of 或者for循環(huán)代替
如下代碼
async function test(){
let readFileFun = [readFileA(),readFileB(),readFileC()] // 數組里的3個方法都是返回Promise的
//異步請求
for(let i = 0; i< readFileFun.length;i++){
let re = await readFileFun[i]
console.log(re)
console.log('end',i+1)
}
}
需求:
數組循環(huán)中獲取異步請求,異步請求全部執(zhí)行完成后做下一個操作,解決方法:
異步請求全部執(zhí)行完后做接下來的工作,可以通過
await Promise.all()
偽代碼如下:
async function printFiles(){
const files = await getFilePaths() // 異步請求獲取文件數組
//通過aysnc await結合map進行循環(huán) 【有序的執(zhí)行異步】
await Promise.all(files.map(async(file) => {
const contents = await fs.readFile('file','utf8') //異步讀取文件
console.log(contents)
})
)
//所以的循環(huán)完成進行下一步的操作
}