【发布时间】:2020-01-23 18:11:14
【问题描述】:
请解释一下,为什么 await 关键字会导致 Hello World 文本放置在中间(第一个示例)和末尾(第二个示例)输出?
第一个例子:
const getData = async() => {
var y = "Hello World";
console.log(y);
}
console.log(1);
getData();
console.log(2);
第一个例子的输出:
1
Hello World
2
第二个例子:
const getData = async() => {
var y = await "Hello World";
console.log(y);
}
console.log(1);
getData();
console.log(2);
第二个例子的输出:
1
2
Hello World
【问题讨论】:
-
因为第二个例子会异步运行。
-
await将导致其余代码延迟到解析后的表达式。它是自动的,但仍会将其余部分转移到微任务队列中。 The beginning of my answer here addresses the behaviour -
我的更多答案在不同的上下文concurrency 和how
awaitaffects execution 中涉及到这一点。哎呀,基本上我所做的任何承诺回答都必须明确提及这种行为......
标签: javascript asynchronous async-await