let x = 0;
async function test() {
x += await 5;
console.log('x :', x);
}
test();
x += 1;
console.log('x :', x);
已x
记录的值为1
和5
。我的问题是:为什么x
5
第二个日志的值是多少?
如果在test
之后执行x += 1
(因为它是异步函数),x
则1
在时间之前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
。
最后,解释器进行加法,将其存储5
到x
并记录下来。
您可以通过在对象属性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] 删除。
我来说两句