gpt4 book ai didi

javascript - arguments.callee 异步时不返回可调用函数

转载 作者:行者123 更新时间:2023-11-29 10:26:39 25 4
gpt4 key购买 nike

我一直在研究 arguments.callee 并偶然发现了这个问题。

我的想法是匿名函数会在启动时运行,然后在几秒钟后再次运行。

setTimeout(async function() {
console.log('Not working')
return arguments.callee
}(), 1000)

如果我的匿名函数不是async,我没有问题

setTimeout(function() {
console.log('Working just fine')
return arguments.callee
}(), 1000)

让我感到困惑的是,当我在 async 函数中 console.log(arguments.callee) 时,它出现得很好。

setTimeout(function() {
console.log(arguments.callee)
}, 1000)

setTimeout(async function() {
console.log(arguments.callee)
}, 2000)

任何人都可以向我解释为什么当函数为 async 时它不起作用吗?

最佳答案

这是因为当您从 async 函数返回一些东西时,它被包装在 Promise 中,所以 arguments.callee 实际上是您要返回的函数,但它包含在一个 promise 中。

来自 MDN :

An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result.

(async function() {
console.log('Not working')
return arguments.callee
}()).then((fun) => fun());
//the wrapped function can be executed in the chained then callback

正如@Oliver Nybo 在评论中指出的那样,我们还可以在 async 上下文中使用 await 来等待使用函数值解析的 promise :

(async () => {
setTimeout(await async function() {
console.log('Not working');
return arguments.callee;
}(), 1000)
})();

关于javascript - arguments.callee 异步时不返回可调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57409218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com