1 分钟读完 JavaScript Async/Await Explained in 10 Minutes
以前我们使用 callback。
后来我们使用 Promise。
现在我们使用 Async/Await。
Async - 定义异步函数(
)
- async function someName(){...}
- await
Await - 暂停异步函数的执行 (
)
- var result = await someAsyncCall();
等待 Promise 完成,并返回 Promise 的结果
- await
只能和 Promise 一起使用,不能和 callback 一起使用
- await
只能用在
- await
函数中
- async
不会。
- Promise.all
- async
- function getABC() {
- let A = await getValueA(); // getValueA 花费 2 秒
- let B = await getValueB(); // getValueA 花费 4 秒
- let C = await getValueC(); // getValueA 花费 3 秒
- return A * B * C;
- }
每次遇到
关键字时,Promise 都会停下在,一直到运行结束,所以总共花费是 2+4+3 = 9 秒。
- await
把异步变成了同步。
- await
- async function getABC() {
- // Promise.all() 允许同时执行所有的异步函数
- let results = await Promise.all([ getValueA, getValueB, getValueC ]);
- return results.reduce((total,value) => total * value);
- }
函数总耗时为 4 秒(
的耗时)。
- getValueB
在 Async/Await 语法中,我们可以使用 try/catch 进行错误处理。在 Promise 中的
分支会进入
- .catch()
语句。
- catch
来源: https://juejin.im/post/59f9c01f6fb9a0452724e9d1