【发布时间】:2021-01-15 21:22:27
【问题描述】:
我正在学习 Javascript。我不习惯异步编程,所以在这里很难。这是我的代码:
var x = 0;
async function increment(x) {
++x;
for (var i = 0; i < 999999999; i = i + 1);
console.log('value of x is: ' + x);
};
increment(x);
console.log('Out of the function');
期望:'Out of the function' 会立即打印出来。 “x 的值...”需要一些时间。
现实:“x 的值...”在延迟后首先打印。然后打印'Out of the function'。
我的问题是,为什么不异步调用 increment()?为什么会阻塞最后一个console.log?
【问题讨论】:
-
大部分答案似乎都是关于解决方案的。但我更期待一些解释为什么我的期望不正确。我想每当我使用 async 时,该函数都不会阻止下一次同步执行——无论是否使用 await。我只是不想让增量函数阻止最后一个 console.log()
-
如果你把 async 放在没有 await 的地方,这个函数会表现得像一个普通的(同步)函数。因此,
increment(x)将阻止最后一个 console.log()。我在我的回答中添加了指向 MDN 的链接,可能有助于更好地理解。 -
@FarhanFuad 查看我的答案,尤其是 Bob-Alice 部分。
标签: javascript node.js asynchronous async-await synchronization