I have been playing around with arguments.callee
and stumbled upon this problem.
My idea was that the anonymous function would run on startup and then again after a few seconds.
setTimeout(async function() { console.log('Not working') return arguments.callee }(), 1000)
I have no issues if my anonymous function isn't async
setTimeout(function() { console.log('Working just fine') return arguments.callee }(), 1000)
The thing has me baffled is that, when I console.log(arguments.callee)
in the async
function, it comes up just fine.
setTimeout(function() { console.log(arguments.callee) }, 1000) setTimeout(async function() { console.log(arguments.callee) }, 2000)
Can anyone explain to me why it doesn't work when the function is async
?
This is because when you return something from an async
function it is wrapped in a Promise , so the arguments.callee
is actually the function you want to return but it is wrapped inside a promise.
From 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
As @ Oliver Nybo pointed out in the comment, we can also use await
inside an async
context to wait for the promise to be resolved with the function value:
(async () => { setTimeout(await async function() { console.log('Not working'); return arguments.callee; }(), 1000) })();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.