Skip to content

async await ​

2023-05-17 16:59:28

promise 解决了回调地狱的问题,改成了链式调用,但是回调过多时还是会有些麻烦。

async await 同步的方式来完成异步的功能。

await 相当于 .then 方法,可以直接拿到成功的 promise 实例化对象的结果值。

async 函数中可以没有 await,但是 await 必须写在 async 函数中。

await 后面的数据 ​

情况一 ​

await 后面为非 promise 类型的数据,那么就直接返回 await 后面的数据。

ts
async function fun() {
  const result = await '123'
  console.log(result)
}

fun()

情况二 ​

await 后面为 promise 成功类型的数据,那么就直接返回 promise 得到的结果值。

ts
async function fun() {
  const result = await new Promise((resolve, reject) => {
    resolve('success')
  })
  console.log(result)
}

fun()

如果这里不加 await,那么返回的是一个 promise 对象,而不是 success 字符串、

情况三 ​

await 后面为 promise 失败类型的数据,那么需要 try catch 来捕获。

ts
async function fun() {
  try {
    const result = await new Promise((resolve, reject) => {
      reject('success')
    })
    console.log(result)
  } catch (err) {
    console.log(err)
  }
  console.log('有了try catch还可以继续执行后续代码')
}

fun()

多个 await 执行顺序 ​

ts
console.log('start')
async function fun() {
  console.log(1)
  const result = await Promise.resolve(2)
  console.log(result)
  console.log(3)
  const result = await Promise.resolve(4)
  console.log(result)
  console.log(5)
}

fun()
console.log('end')

Released under the MIT License.