await

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
  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值