Async/await 和 Promises 區別

原文地址=> 6 Reasons Why JavaScript’s Async/Await Blows Promises Away (Tutorial)

Async/await 是創建在 Promises上的,不能被使用在普通回調以及節點回調javascript

Async/await 和 Promises 很像,不阻塞java

Async/await 代碼看起來像同步代碼。promise

語法

假設函數getJSON返回值是 Promise,而且 Promise resolves 有一些JSON 對象。咱們只想調用它而且記錄該JSON而且返回完成。async

使用Promise函數

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

makeRequest()

使用Asyncoop

const makeRequest = async() => {
        console.log(await getJSON)
        return "done"
}

makeRequest()

區別

  1. 在函數前有一個關鍵字asyncawait關鍵字只能在使用async定義的函數中使用。任何一個async函數都會隱式返回一個promise,而且promise resolve 的值就是 return 返回的值 (例子中是」done」)
  2. 不能在函數開頭使用await

有哪些好處

  1. 簡潔的代碼

使用async函數能夠讓代碼簡潔不少,不須要像Promise同樣須要些thenthis

  1. 錯誤處理

Promise 中不能自定義使用 try/catch 進行錯誤捕獲,可是在 Async/await 中能夠像處理同步代碼處理錯誤code

const makeRequest = () => {
  try {
    getJSON()
      .then(result => {
        // this parse may fail
        const data = JSON.parse(result)
        console.log(data)
      })
      // uncomment this block to handle asynchronous errors
      // .catch((err) => {
      //   console.log(err)
      // })
  } catch (err) {
    console.log(err)
  }
}

Async/await對象

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

條件語句也和錯誤捕獲是同樣的,在 Async 中也能夠像平時通常使用條件語句ip

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

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    
  }
}
  1. 中間值

在一些場景中,也許須要 promise1 去觸發 promise2 再去觸發 promise3,這個時候代碼應該是這樣的

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

如過 promise3 不須要 value1,嵌套將會變得簡單。若是你有強迫症,則將值1&2使用 promise.all() 分裝起來。

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

可是使用 Async 就會變得很簡單

const makeRequest = async () => {
  const value1 = await promise1()
  const value2 = await promise2(value1)
  return promise3(value1, value2)
}
  1. 錯誤棧

如過 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 就不同了

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)
  })
相關文章
相關標籤/搜索