await 的认知

先说明await后面跟的两种情况,await等待的是后面promise的执行结果
01:不是promsie(此时会将跟的值,转换为promise对象,promise.resolve(val)),
02:  promise 直接运行promise.resolve(val)

1.题目解析说明
var a = 0;
var fn =  async()=>{
        a = a + await 10; 
       console.log(a);
};
fn();
console.log(++a);

解析:
01: async是个同步函数,执行到a = a + await 10时候,碰到 await 10, 此时 a + await 10中的a = 0; 
02:先把 await 10 包装成promise.resolve(10);
03:await 在等待promise.resolve(10).then(re s=> res)执行结果
04:由于等待的是then(微任务)的执行结果
05:此时执行async()函数外的代码console.log(a) ,此时的a=1;外部代码执行完毕
06:返回async()函数中,await 等待then(res=> res)执行结果10返回,
07: a = 0 + 10 



2.题目解析说明
var a = 0;
var fn =  async()=>{
        a = (await  a) +10; 
       console.log(a);
};
fn();
console.log(++a);

解析:
01: async是个同步函数,执行到a =  (await  a) +10时候,碰到 await a, 此时 a = 0; 
02:先把await 0 包装成promise.resolve(0);
03:await 在等待promise.resolve(0).then(re s=> res)执行结果
04:由于等待的是then(微任务)的执行结果
05:此时执行async()函数外的代码console.log(a) ,此时的a=1;外部代码执行完毕
06:返回async()函数中,await 等待then(res=> res)执行结果0返回,
07: a = 0 + 10 

3.题目解析说明
var a = 0;
var fn =  async()=>{
        await ( a = a +10); 
       console.log(a);
};
fn();
console.log(++a);

解析:
01: async是个同步函数,执行到await ( a = a +10)时候,先计算表达式的值 await (a = 10), 此时a = 10; 
02:先把await 10 包装成promise.resolve(10);
03:await 在等待promise.resolve(10).then(res=> res)执行结果
04:由于等待的是then(微任务)的执行结果
05:此时执行async()函数外的代码console.log(a) ,此时的a=11(await ( a = a +10)时,a = 10了);外部代码执行完毕
06:返回async()函数中,await 等待then(res=> res)执行结果10返回,
07: console.log(a), 此时的a=11

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值