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 = async () => {
        await callAPromise()
        await callAPromise()
        await callAPromise()
        await callAPromise()
        await callAPromise()
        throw new Error("oops");
    }

    makeRequest().catch(err => {
        console.log(err);
        // output
        // Error: oops at makeRequest (index.js:7:9)
    })
復制代碼

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

   《1》不能在返回表達式的箭頭函數中設置斷點
   《2》如果你在.then代碼塊中設置斷點,使用Step Over快捷鍵,調試器不會跳到下一個.then,因為它只會跳過異步代碼。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM