async/await 是什么?
-
async/await 是 ES2017 中新增的异步解决方案;
-
await 只能在异步函数 async 中使用;
-
async 返回一个 Promise 对象;
-
await 等待一个 Promise 对象。
如何使用?
- 一个
async 异步函数可以包含 0 个或多个 await 指令,当代码运行到 await 的时候,该函数会进入等待模式并转让控制权,直到被等待的 Promise 被 resolved() 或者 rejected() 为止;
- 如果
Promise 被 resolve() 则以返回值的形式传递到等待中的 await 表达式中,并执行之后的代码;
const pm = function () {
return new Promise(resolve => {
setTimeout(() => {
console.log("pm");
resolve("ok");
}, 2000);
});
};
async function aa() {
await pm().then(res => {
console.log(res);
});
// 接下来要被执行的代码
console.log(`aa`);
}
aa();
pm // 2000ms later
ok
aa
- 如果
Promise 被 reject() 则 await 之后的代码不会被执行,此时可以使用 try/catch 进行捕获。
const pm = function () {
return new Promise((resolve, reject) => {
console.log("pm");
reject();
});
};
async function aa() {
try {
await pm().then(res => {
console.log(res);
});
} catch {
console.log(`aa`);
}
}
aa();
pm
aa