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)
  })
相关文章
相关标签/搜索