JS 中的 async/await
2020-09-23 本文已影响0人
limengzhe
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