天天看點

前端javaScript promise屬性與async和await的差別

前端javaScript promise屬性與async和await的差別

 什麼是async/await?

async/await是寫異步代碼的新方式,以前的方法有回調函數和Promise。

async/await是基于Promise實作的,它不能用于普通的回調函數。

async/await與Promise一樣,是非阻塞的。

async/await使得異步代碼看起來像同步代碼,這正是它的魔力所在。

 async/await文法:

假設函數getJSON傳回值是 Promise,并且 Promise resolves 有一些JSON 對象。我們隻想調用它并且記錄該JSON并且傳回完成。

1)使用Promise:

const makeRequest = () =>
        getJSON().then(data => {
            console.log(data)
            return "done"
        })

    makeRequest()      

2)使用Async

const makeRequest = async () => {
        // await getJSON()表示console.log會等到getJSON的promise成功reosolve之後再執行。
        console.log(await getJSON)
        return "done"
    }

    makeRequest()      

差別:

1)函數前面多了一個aync關鍵字。await關鍵字隻能用在aync定義的函數内。async函數會隐式地傳回一個promise,該promise的reosolve值就是函數return的值。(示例中reosolve值就是字元串”done”)

2)第1點暗示我們不能在最外層代碼中使用await,因為不在async函數内。例如:

// 不能在最外層代碼中使用await
    await makeRequest()

    // 這是會出事情的 
    makeRequest().then((result) => {
        // 代碼
    })      

為什麼Async/Await更好?

1)使用async函數可以讓代碼簡潔很多,不需要像Promise一樣需要些then,不需要寫匿名函數處理Promise的resolve值,也不需要定義多餘的data變量,還避免了嵌套代碼。

2) 錯誤處理:

    Async/Await 讓 try/catch 可以同時處理同步和異步錯誤。在下面的promise示例中,try/catch 不能處理 JSON.parse 的錯誤,因為它在Promise中。我們需要使用 .catch,這樣錯誤處理代碼非常備援。并且,在我們的實際生産代碼會更加複雜。

const makeRequest = () => {
        try {
            getJSON().then(result => {
                // JSON.parse可能會出錯
                const data = JSON.parse(result)
                console.log(data)
            })
            // 取消注釋,處理異步代碼的錯誤
            // .catch((err) => {
            //   console.log(err)
            // })
        } catch (err) {
            console.log(err)
        }
    }      

使用aync/await的話,catch能處理JSON.parse錯誤:

const makeRequest = async () => {
        try {
            // this parse may fail
            const data = JSON.parse(await getJSON())
            console.log(data)
        } catch (err) {
            console.log(err)
        }
    }      

3)條件語句

條件語句也和錯誤捕獲是一樣的,在 Async 中也可以像平時一般使用條件語句

Promise:
const makeRequest = () => {
        return getJSON().then(data => {
            if (data.needsAnotherRequest) {
                return makeAnotherRequest(data).then(moreData => {
                    console.log(moreData)
                    return moreData
                })
            } else {
                console.log(data)
                return data
            }
        })
    }      

async/await:

const makeRequest = async () => {
        const data = await getJSON()
        if (data.needsAnotherRequest) {
            const moreData = await makeAnotherRequest(data);
            console.log(moreData)
            return moreData
        } else {
            console.log(data)
            return data
        }
    }      

4)中間值

你很可能遇到過這樣的場景,調用promise1,使用promise1傳回的結果去調用promise2,然後使用兩者的結果去調用promise3。

const makeRequest = () => {
        return promise1().then(value1 => {
            return promise2(value1).then(value2 => {
                return promise3(value1, value2)
            })
        })
    }      

如果 promise3 不需要 value1,嵌套将會變得簡單。如果你忍受不了嵌套,你可以将value 1 & 2 放進Promise.all來避免深層嵌套,但是這種方法為了可讀性犧牲了語義。除了避免嵌套,并沒有其他理由将value1和value2放在一個數組中。

const makeRequest = () => {
        return promise1().then(value1 => {
            return Promise.all([value1, promise2(value1)])
        }).then(([value1, value2]) => {
            return promise3(value1, value2)
        })
    }      

使用async/await的話,代碼會變得異常簡單和直覺。

const makeRequest = async () => {
        const value1 = await promise1()
        const value2 = await promise2(value1)
        return promise3(value1, value2)
    }      

5)錯誤棧

如果 Promise 連續調用,對于錯誤的處理是很麻煩的。你無法知道錯誤出在哪裡。

const makeRequest = () => {
        return callAPromise()
            .then(() => callAPromise())
            .then(() => callAPromise())
            .then(() => callAPromise())
            .then(() => callAPromise())
            .then(() => {
                throw new Error("oops");
            })
    }

    makeRequest().catch(err => {
        console.log(err);
        // output
        // Error: oops at callAPromise.then.then.then.then.then (index.js:8:13)
    })      

async/await中的錯誤棧會指向錯誤所在的函數。在開發環境中,這一點優勢并不大。但是,當你分析生産環境的錯誤日志時,它将非常有用。這時,知道錯誤發生在makeRequest比知道錯誤發生在then鍊中要好。

const makeRequest = () => {
        return callAPromise()
            .then(() => callAPromise())
            .then(() => callAPromise())
            .then(() => callAPromise())
            .then(() => callAPromise())
            .then(() => {
                throw new Error("oops");
            })
    }

    makeRequest().catch(err => {
        console.log(err);
        // output
        // Error: oops at callAPromise.then.then.then.then.then (index.js:8:13)
    })      

6)調試

async/await能夠使得代碼調試更簡單。2個理由使得調試Promise變得非常痛苦:

   《1》不能在傳回表達式的箭頭函數中設定斷點

   《2》如果你在.then代碼塊中設定斷點,使用Step Over快捷鍵,調試器不會跳到下一個.then,因為它隻會跳過異步代碼。

   使用await/async時,你不再需要那麼多箭頭函數,這樣你就可以像調試同步代碼一樣跳過await語句。

繼續閱讀