async-await

2021/5/12 JavaScript

源链接:https://juejin.cn/post/6960855679208783903 (opens new window)

# 语法

async/await 是一种编写异步代码的新方法。在这之前编写异步代码使用的回调函数和 promise。

async/await 实际是建立在 promise 之上的。因此你不能把它和回调函数搭配使用。

async/await 可以使异步代码在形式上更接近于同步代码。这就是它最大的价值。

假设有一个 getJSON 方法,它返回一个 promise,该 promise 会被 resolve为一个 JSON 对象。我们想要调用该方法,输出得到的 JSON 对象,最后返回 "done"。

以下是使用promise的实现方式:

const makeRequest = () =>
  getJSON()
    .then(data => {
      console.log(data)
      return "done"
    })
makeRequest()
1
2
3
4
5
6
7

使用async/await 则是这样的:

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

makeRequest()
1
2
3
4
5
6

await getJSON() 意味着直到 getJSON() 返回的 promise 在 resolve 之后,console.log 才会执行并输出 resolove 的值。

使用 async/await 时有以下几个区别:

在定义函数时我们使用了 async 关键字。await 关键字只能在使用 async 定义的函数的内部使用。所有 async 函数都会返回一个 promise,该 promise 最终 resolve 的值就是你在函数中 return 的内容。 由于第一点中的原因,你不能在顶级作用域中 await 一个函数。因为顶级作用域不是一个 async 方法。

// this will not work in top level
// await makeRequest()
    
// this will work
makeRequest().then((result) => {
  // do something
})
1
2
3
4
5
6
7

# 为何使用async/await编写出来的代码更好呢?

# 简洁

我们不需要为.then编写一个匿名函数来处理返回结果,也不需要创建一个data变量来保存我们实际用不到的值。我们还避免了代码嵌套。这些小优点会在真实项目中变得更加明显。

# 错误处理

async/await 终于使得用同一种构造(古老而好用的try/catch) 处理同步和异步错误成为可能。在下面这段使用 promise 的代码中,try/catch 不能捕获 JSON.parse 抛出的异常,因为该操作是在 promise 中进行的。要处理 JSON.parse 抛出的异常,你需要在 promise 上调用 .catch 并重复一遍异常处理的逻辑。通常在生产环境中异常处理逻辑都远比 console.log 要复杂,因此这会导致大量的冗余代码。

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)
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

现在看看使用了 async/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)
  }
}
1
2
3
4
5
6
7
8
9

# 条件分支

假设有如下逻辑的代码。请求数据,然后根据返回数据中的某些内容决定是直接返回这些数据还是继续请求更多数据:

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
      }
    })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

只是阅读这些代码已经够让你头疼的了。一不小心你就会迷失在这些嵌套(6层),空格,返回语句中。

在使用 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    
  }
}
1
2
3
4
5
6
7
8
9
10
11

# 中间值

你可能会遇到这种情况,请求 promise1,使用它的返回值请求 promise2,最后使用这两个 promise 的值请求 promise3。对应的代码看起来是这样的:

const makeRequest = () => {
  return promise1()
    .then(value1 => {
      // do something
      return promise2(value1)
        .then(value2 => {
          // do something          
          return promise3(value1, value2)
        })
    })
}
1
2
3
4
5
6
7
8
9
10
11

如果 promise3 没有用到 value1,那么我们就可以把这几个 promise 改成嵌套的模式。如果你不喜欢这种编码方式,你也可以把 value1 和 value2 封装在一个 Promsie.all 调用中以避免深层次的嵌套:

const makeRequest = () => {
  return promise1()
    .then(value1 => {
      // do something
      return Promise.all([value1, promise2(value1)])
    })
    .then(([value1, value2]) => {
      // do something          
      return promise3(value1, value2)
    })
}
1
2
3
4
5
6
7
8
9
10
11

这种方式为了保证可读性而牺牲了语义。除了避免嵌套的 promise,没有其它理由要把 value1 和 value2 放到一个数组里。

同样的逻辑如果换用 async/await 编写就会非常简单,直观。

const makeRequest = async () => {
  const value1 = await promise1()
  const value2 = await promise2(value1)
  return promise3(value1, value2)
}
1
2
3
4
5

# 异常堆栈

假设有一段串行调用多个promise的代码,在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)
  })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

从 promise 串返回的异常堆栈中没有包含关于异常是从哪一个环节抛出的信息。更糟糕的是,它还会误导你,它包含的唯一的函数名是 callAPromise,然而该函数与此异常并无关系。(这种情况下文件名和行号还是有参考价值的)。

然而,在使用了 async/await 的代码中,异常堆栈指向了正确的函数:

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)
  })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

这带来的好处在本地开发环境中可能并不明显,但当你想要在生产环境的服务器上获取有意义的异常信息时,这会非常有用。在这种情况下,知道异常来自 makeRequest 而不是一连串的 then 调用会有意义的多。

# 调试

最后压轴的一点,使用async/await最大的优势在于它很容易被调试。由于以下两个原因,调试 promise 一直以来都是很痛苦的。

你不能在一个返回表达式的箭头函数中设置断点(因为没有代码块)

const makeRequest = () => {
  return callAPromise()
    .then(() => callAPromise())
    .then(() => callAPromise())
    .then(() => callAPromise())
    .then(() => callAPromise())
}
1
2
3
4
5
6
7

如果你在一个.then代码块中使用调试器的步进(step-over)功能,调试器并不会进入后续的.then代码块,因为调试器只能跟踪同步代码的『每一步』。

通过使用 async/await,你不必再使用箭头函数。你可以对 await 语句执行步进操作,就好像他们都是普通的同步调用一样。

const makeRequest = async () => {
  await callAPromise()
  await callAPromise()
  await callAPromise()
  await callAPromise()
  await callAPromise()
}
1
2
3
4
5
6
7

结论 async/await 是过去几年中 JavaScript 引入的最具革命性的特性之一。它使你意识到 promise 在语法上的糟糕之处,并提供了一种简单,直接的替代方案。

Last Updated: 2023/04/22, 23:39:26
彩虹
周杰伦