提问人:Arghya Saha 提问时间:11/15/2023 最后编辑:Arghya Saha 更新时间:11/15/2023 访问量:56
这个异步函数片段如何在 JS 的执行上下文中工作?
How does this async function snippet work in the execution context in JS?
问:
我正在学习 Javascript,我遇到了 JS 片段。我不明白它是如何工作的
let hello = () => Promise.resolve("Hello")
async function fun() {
console.log("Inside")
const result = await hello()
console.log(result)
}
console.log("Start")
fun()
console.log("End")
控制台中的结果
Start
Inside
End
Hello
我不明白为什么尽管使用了 await 关键字,但 End 会在 Hello 之前打印。我想了解这个片段在事件循环中是如何工作的。更具体地说,当 fun() 被推送到调用堆栈中时会发生什么
答:
2赞
Adrid
11/15/2023
#1
在您的代码中仅用作异步函数。hello
您将 file 函数作为异步函数,但它不起作用,因为当您调用 时,您不使用 .fun
fun
await
我在下面添加代码。
let hello = () => Promise.resolve("Hello");
async function fun() {
console.log("Inside");
const result = await hello();
console.log(result);
}
const main = async () => {
console.log("Start");
await fun();
console.log("End");
};
main();
1赞
Amit Mohanty
11/15/2023
#2
在 中,当调用异步函数时,它不会阻止后续代码的执行。函数内部的关键字会导致函数暂停和等待,但不会阻止函数外部其他代码的执行。这就是为什么“End”打印在“Hello”之前的原因。JavaScript
await
async
async
评论