說明:轉載至自 邊城的理解 JavaScript 的 async/await
async 和 await 在干什么
任意一個名稱都是有意義的,先從字面意思來理解,async 是“異步”的簡寫,而 await 可以認為是 async wait 的簡寫,所以應該很好理解 async 用于申明一個 function 是異步的,而 await 用于等待一個異步方法執行完成,
另外還有一個很有意思的語法規定,await 只能出現在 async 函式中,然后細心的朋友會產生一個疑問,如果 await 只能出現在 async 函式中,那這個 async 函式應該怎么呼叫?
如果需要通過 await 來呼叫一個 async 函式,那這個呼叫的外面必須得再包一個 async 函式,然后……進入死回圈,永無出頭之日……
如果 async 函式不需要 await 來呼叫,那 async 到底起個啥作用?
async 起什么作用
這個問題的關鍵在于,async 函式是怎么處理它的回傳值的!
我們當然希望它能直接通過 return 陳述句回傳我們想要的值,但是如果真是這樣,似乎就沒 await 什么事了,所以,寫段代碼來試試,看它到底會回傳什么:
async function testAsync() { return "hello async"; } const result = testAsync(); console.log(result);
看到輸出就恍然大悟了——輸出的是一個 Promise 物件,
c:\var\test> node --harmony_async_await .
Promise { 'hello async' }
所以,async 函式回傳的是一個 Promise 物件,從檔案中也可以得到這個資訊,async 函式(包含函式陳述句、函式運算式、Lambda運算式)會回傳一個 Promise 物件,如果在函式中 return 一個直接量,async 會把這個直接量通過 Promise.resolve() 封裝成 Promise 物件,
async 函式回傳的是一個 Promise 物件,所以在最外層不能用 await 獲取其回傳值的情況下,我們當然應該用原來的方式:then() 鏈來處理這個 Promise 物件,就像這樣
testAsync().then(v => { console.log(v); // 輸出 hello async });
現在回過頭來想下,如果 async 函式沒有回傳值,又該如何?很容易想到,它會回傳 Promise.resolve(undefined),
聯想一下 Promise 的特點——無等待,所以在沒有 await 的情況下執行 async 函式,它會立即執行,回傳一個 Promise 物件,并且,絕不會阻塞后面的陳述句,這和普通回傳 Promise 物件的函式并無二致,
那么下一個關鍵點就在于 await 關鍵字了,
await 到底在等啥
一般來說,都認為 await 是在等待一個 async 函式完成,不過按語法說明,await 等待的是一個運算式,這個運算式的計算結果是 Promise 物件或者其它值(換句話說,就是沒有特殊限定),
因為 async 函式回傳一個 Promise 物件,所以 await 可以用于等待一個 async 函式的回傳值——這也可以說是 await 在等 async 函式,但要清楚,它等的實際是一個回傳值,注意到 await 不僅僅用于等 Promise 物件,它可以等任意運算式的結果,所以,await 后面實際是可以接普通函式呼叫或者直接量的,所以下面這個示例完全可以正確運行
function getSomething() { return "something"; } async function testAsync() { return Promise.resolve("hello async"); } async function test() { const v1 = await getSomething(); const v2 = await testAsync(); console.log(v1, v2); } test();
await 等到了要等的,然后呢
await 等到了它要等的東西,一個 Promise 物件,或者其它值,然后呢?我不得不先說,await 是個運算子,用于組成運算式,await 運算式的運算結果取決于它等的東西,
如果它等到的不是一個 Promise 物件,那 await 運算式的運算結果就是它等到的東西,
如果它等到的是一個 Promise 物件,await 就忙起來了,它會阻塞后面的代碼,等著 Promise 物件 resolve,然后得到 resolve 的值,作為 await 運算式的運算結果,
看到上面的阻塞一詞,心慌了吧……放心,這就是 await 必須用在 async 函式中的原因,async 函式呼叫不會造成阻塞,它內部所有的阻塞都被封裝在一個 Promise 物件中異步執行,
async/await 幫我們干了啥
作個簡單的比較
上面已經說明了 async 會將其后的函式(函式運算式或 Lambda)的回傳值封裝成一個 Promise 物件,而 await 會等待這個 Promise 完成,并將其 resolve 的結果回傳出來,
現在舉例,用 setTimeout 模擬耗時的異步操作,先來看看不用 async/await 會怎么寫
function takeLongTime() { return new Promise(resolve => { setTimeout(() => resolve("long_time_value"), 1000); }); } takeLongTime().then(v => { console.log("got", v); });
如果改用 async/await 呢,會是這樣
function takeLongTime() { return new Promise(resolve => { setTimeout(() => resolve("long_time_value"), 1000); }); } async function test() { const v = await takeLongTime(); console.log(v); } test();
眼尖的同學已經發現 takeLongTime() 沒有申明為 async,實際上,takeLongTime() 本身就是回傳的 Promise 物件,加不加 async 結果都一樣,如果沒明白,請回過頭再去看看上面的“async 起什么作用”,
又一個疑問產生了,這兩段代碼,兩種方式對異步呼叫的處理(實際就是對 Promise 物件的處理)差別并不明顯,甚至使用 async/await 還需要多寫一些代碼,那它的優勢到底在哪?
async/await 的優勢在于處理 then 鏈
單一的 Promise 鏈并不能發現 async/await 的優勢,但是,如果需要處理由多個 Promise 組成的 then 鏈的時候,優勢就能體現出來了(很有意思,Promise 通過 then 鏈來解決多層回呼的問題,現在又用 async/await 來進一步優化它),
假設一個業務,分多個步驟完成,每個步驟都是異步的,而且依賴于上一個步驟的結果,我們仍然用 setTimeout 來模擬異步操作:
/** * 傳入引數 n,表示這個函式執行的時間(毫秒) * 執行的結果是 n + 200,這個值將用于下一步驟 */ function takeLongTime(n) { return new Promise(resolve => { setTimeout(() => resolve(n + 200), n); }); } function step1(n) { console.log(`step1 with ${n}`); return takeLongTime(n); } function step2(n) { console.log(`step2 with ${n}`); return takeLongTime(n); } function step3(n) { console.log(`step3 with ${n}`); return takeLongTime(n); }
現在用 Promise 方式來實作這三個步驟的處理
function doIt() { console.time("doIt"); const time1 = 300; step1(time1) .then(time2 => step2(time2)) .then(time3 => step3(time3)) .then(result => { console.log(`result is ${result}`); console.timeEnd("doIt"); }); } doIt(); // c:\var\test>node --harmony_async_await . // step1 with 300 // step2 with 500 // step3 with 700 // result is 900 // doIt: 1507.251ms
輸出結果 result 是 step3() 的引數 700 + 200 = 900,doIt() 順序執行了三個步驟,一共用了 300 + 500 + 700 = 1500 毫秒,和 console.time()/console.timeEnd() 計算的結果一致,
如果用 async/await 來實作呢,會是這樣
async function doIt() { console.time("doIt"); const time1 = 300; const time2 = await step1(time1); const time3 = await step2(time2); const result = await step3(time3); console.log(`result is ${result}`); console.timeEnd("doIt"); } doIt();
結果和之前的 Promise 實作是一樣的,但是這個代碼看起來是不是清晰得多,幾乎跟同步代碼一樣
還有更酷的
現在把業務要求改一下,仍然是三個步驟,但每一個步驟都需要之前每個步驟的結果,
function step1(n) { console.log(`step1 with ${n}`); return takeLongTime(n); } function step2(m, n) { console.log(`step2 with ${m} and ${n}`); return takeLongTime(m + n); } function step3(k, m, n) { console.log(`step3 with ${k}, ${m} and ${n}`); return takeLongTime(k + m + n); }
這回先用 async/await 來寫:
async function doIt() { console.time("doIt"); const time1 = 300; const time2 = await step1(time1); const time3 = await step2(time1, time2); const result = await step3(time1, time2, time3); console.log(`result is ${result}`); console.timeEnd("doIt"); } doIt(); // c:\var\test>node --harmony_async_await . // step1 with 300 // step2 with 800 = 300 + 500 // step3 with 1800 = 300 + 500 + 1000 // result is 2000 // doIt: 2907.387ms
除了覺得執行時間變長了之外,似乎和之前的示例沒啥區別啊!別急,認真想想如果把它寫成 Promise 方式實作會是什么樣子?
function doIt() { console.time("doIt"); const time1 = 300; step1(time1) .then(time2 => { return step2(time1, time2) .then(time3 => [time1, time2, time3]); }) .then(times => { const [time1, time2, time3] = times; return step3(time1, time2, time3); }) .then(result => { console.log(`result is ${result}`); console.timeEnd("doIt"); }); } doIt();
有沒有感覺有點復雜的樣子?那一堆引數處理,就是 Promise 方案的死穴—— 引數傳遞太麻煩了,看著就暈!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/138146.html
標籤:JavaScript
下一篇:Ajax的原理及封裝
