問題
這里有個問題為什么從列表中選擇披薩這個動作要等待獲取飲料列表?這兩個是沒什么關(guān)聯(lián)的操作。其中的關(guān)聯(lián)操作有兩組:
獲取披薩列表 -》 選擇披薩 -》 選擇披薩加入購物車
獲取飲料列表 -》 選擇飲料 -》 選擇飲料加入購物車
這兩組操作應(yīng)該是并發(fā)執(zhí)行的。
再來看一個更差的例子
這個 Javascript 代碼片段將購物車中的商品并發(fā)出訂購請求。
async function orderItems() { const items = await getCartItems() // async call const noOfItems = items.length for(var i = 0; i < noOfItems; i++) { await sendRequest(items[i]) // async call } }
這種情況 for 循環(huán)必須等待 sendRequest() 函數(shù)完成才能繼續(xù)下一次迭代。但是,我們并不需要等待。我們希望盡快發(fā)送所有請求。然后我們可以等待所有請求完成。
現(xiàn)在你應(yīng)該已經(jīng)對 async/await 地獄有跟多的了解,現(xiàn)在我們再來考慮一個問題
如果我們忘記 await 關(guān)鍵字會怎么樣?
如果在調(diào)用異步函數(shù)忘記使用 await,這意味著執(zhí)行該功能不需要等待。異步函數(shù)將直接返回一個 promise,你可以稍后使用。
(async () => { const value = doSomeAsyncTask() console.log(value) // an unresolved promise })()
或者是程序不清楚你想要等待函數(shù)執(zhí)行完,直接退出不會完成這個異步任務(wù)。所以我們需要使用 await 這個關(guān)鍵字。
promise 有一個有趣的屬性,你可以在某行代碼中獲取 promise,然后在其他地方中等待它 resolve,這是解決 async/await 地獄的關(guān)鍵。
(async () => { const promise = doSomeAsyncTask() const value = await promise console.log(value) // the actual value })()
如你所見 doSomeAsyncTask 直接返回一個 Promise 同時這個異步函數(shù) doSomeAsyncTask 已經(jīng)開始執(zhí)行,為了得到 doSomeAsyncTask 的返回值,我們需要 await 來告訴
應(yīng)該如何避免 async/await 地獄
首先我們需要知道哪些命名是有前后依賴關(guān)系的。
然后將有依賴關(guān)系的系列操作進行分組合并成一個異步操作。
同時執(zhí)行這些異步函數(shù)。
我們來重寫這寫例子:
async function selectPizza() { const pizzaData = await getPizzaData() // async call const chosenPizza = choosePizza() // sync call await addPizzaToCart(chosenPizza) // async call } async function selectDrink() { const drinkData = await getDrinkData() // async call const chosenDrink = chooseDrink() // sync call await addDrinkToCart(chosenDrink) // async call } (async () => { const pizzaPromise = selectPizza() const drinkPromise = selectDrink() await pizzaPromise await drinkPromise orderItems() // async call })() // Although I prefer it this way (async () => { Promise.all([selectPizza(), selectDrink()].then(orderItems) // async call })()
我們將語句分成兩個函數(shù)。在函數(shù)內(nèi)部,每個語句都依賴于前一個語句的執(zhí)行。然后我們同時執(zhí)行這兩個函數(shù) selectPizza()和selectDrink() 。
在第二個例子中我們需要處理未知數(shù)量的 Promise。處理這個問題非常簡單,我們只需要創(chuàng)建一個數(shù)組將所有 Promise 存入其中,使用 Promise.all() 方法并行執(zhí)行:
async function orderItems() { const items = await getCartItems() // async call const noOfItems = items.length const promises = [] for(var i = 0; i < noOfItems; i++) { const orderPromise = sendRequest(items[i]) // async call promises.push(orderPromise) // sync call } await Promise.all(promises) // async call }
總結(jié)
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com