await
操作符用于等待一个Promise 对象。它只能在异步函数 async function 中使用。(The await operator is used to wait for a Promise. It can only be used inside an async function.)
语法
[return_value] = await expression;
参数:
- expression:一个 Promise 对象或者任何要等待的值。
- return_value: 返回 Promise 对象的处理结果。如果等待的不是 Promise 对象,则返回该值本身。
await 表达式会暂停当前 async function 的执行,等待 Promise 处理完成。若 Promise 正常处理(fulfilled),其回调的resolve函数参数 作为 await 表达式的值,接着继续执行 async function。若 Promise 处理异常(rejected),await 表达式会把 Promise 的异常原因抛出。另外,如果 await 操作符后的表达式的值不是一个 Promise,await 会把该值转换为已正常处理的Promise并等待结果返回。(If the value of the expression following the await operator is not a Promise, it’s converted to a resolved Promise.)
举例一:如果一个 Promise 被传递给一个 await 操作符,await 将等待 Promise 正常处理完成并返回其处理结果
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
})
}
async function f1() {
let x = await resolveAfter2Seconds('happy chen');
console.log(x);
}
f1();
console.log(f1());
console.log(f1);
//立即输出
// Promise { <pending> }
// [AsyncFunction: f1]
//2s后输出
// happy chen
// happy chen
举例二:如果该值不是一个 Promise,await 会把该值转换为已正常处理的Promise并等待结果返回
async function f1(){
let x = await 'happy chen';
console.log(x);
}
f1();
console.log(f1());
console.log(f1);
// Promise { <pending> }
// [AsyncFunction: f1]
// happy chen
// happy chen
举例三:如果 Promise 处理异常,则异常值被抛出
async function f1() {
try {
let x = await Promise.reject('something wrong');
} catch (e) {
console.log(e);
}
}
f1();
console.log(f1());
console.log(f1);
// Promise { <pending> }
// [AsyncFunction: f1]
// something wrong
// something wrong