理解async/await

async 和 await 在幹什麼

任意一個名稱都是有意義的,先從字面意思來理解。async 是「非同步」的簡寫而 await 可以認為是 async wait 的簡寫。所以應該很好理解 async 用於申明一個 function 是非同步的而 await 用於等待一個非同步方法執行完成

另外還有一個很有意思的語法規定,await 只能出現在 async 函數中。然後細心的朋友會產生一個疑問,如果 await 只能出現在 async 函數中,那這個 async 函數應該怎麼調用?

如果需要通過 await 來調用一個 async 函數,那這個調用的外面必須得再包一個 async 函數,然後……進入死循環,永無出頭之日……

如果 async 函數不需要 await 來調用,那 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();//something hello async

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  至於這裡為什麼沒有設定值還列印的緣故就是,這個運算是先賦值,後++,所以第一次返回的數字是300,依次類推,就算沒有回調函數依舊能返回數據。我嘗試過再後面加了一個then(so = > {console.log(so})返回underfind
// doIt: 1507.251ms

輸出結果 result 是 step3() 的參數 700 + 200 = 900doIt() 順序執行了三個步驟,一共用了 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 方案的死穴—— 參數傳遞太麻煩了,看著就暈!

轉載:作者:邊城客棧

           地址://segmentfault.com/a/1190000007535316

大神說得很好,版面比我排得好看,要是看到這篇文章的讀者,可以去看看原作者的文章啊

Tags: