+ =的异步功能

阿德林·文森特

let x = 0;

async function test() {
    x += await 5;
    console.log('x :', x);
}

test();
x += 1;
console.log('x :', x);

x记录的值为15我的问题是:为什么x 5第二个日志的值是多少?

如果在test之后执行x += 1(因为它是异步函数),x1在时间之前test执行isx += await 5的值,因此应将value设为x 6

防区

TL; DR:由于其第二个操作数(右侧)中关键字,因此在更改之前先+=读取,x然后写入await


async函数在调用直到第一条await语句时同步运行

因此,如果删除await,它的行为就像普通函数一样(除了它仍然返回Promise)。

在这种情况下,您将在控制台中5(从函数)和6(从主脚本)获取:

let x = 0;

async function test() {
  x += 5;
  console.log('x :', x);
}

test();
x += 1;
console.log('x :', x);


第一个会await停止同步运行,即使其参数可以同步使用,因此也可以按照您的期望返回1(从主脚本)和6(从函数):

let x = 0;

async function test() {
  // Enter asynchrony
  await 0;

  x += 5;
  console.log('x :', x);
}

test();
x += 1;
console.log('x :', x);


但是,您的情况要复杂一些。

您已将await表达式放入,并使用+=

您可能知道,在JSx += y中与相同x = (x + y)我将使用后一种形式来更好地理解:

let x = 0;

async function test() {
  x = (x + await 5);
  console.log('x :', x);
}

test();
x += 1;
console.log('x :', x);

当口译员到达这一行时...

x = (x + await 5);

...开始评估它,替代x它,因此变成...

x = (0 + await 5);

...然后,它到达await并停止。

函数调用后的代码开始运行,并修改的值x,然后将其记录下来。

x现在1

然后,在退出主脚本后,解释器将返回暂停的test功能,并继续评估该行:

x = (0 + 5);

并且,由于的值x已被替换,因此仍为0

最后,解释器进行加法,将其存储5x并记录下来。

您可以通过在对象属性getter / setter中登录来检查此行为(在此示例中,y.z反映了的值x

let x = 0;
const y = {
  get z() {
    console.log('get x :', x);
    return x;
  },
  set z(value) {
    console.log('set x =', value);
    x = value;
  }
};

async function test() {
  console.log('inside async function');
  y.z += await 5;
  console.log('x :', x);
}

test();
console.log('main script');
y.z += 1;
console.log('x :', x);

/* Output:

inside async function
get x : 0   <-- async fn reads
main script
get x : 0
set x = 1
x : 1
set x = 5   <-- async fn writes
x : 5       <-- async fn logs

*/
/* Just to make console fill the available space */
.as-console-wrapper {
  max-height: 100% !important;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章