function foo()
{
let a = 5;
setTimeout(function(){a = 6;}, 1000);
return a;
}
How can I return 6 for foo
? The asynchronous function I am using is actually from a framework, not setTimeout
.
function foo()
{
let a = 5;
setTimeout(function(){a = 6;}, 1000);
return a;
}
How can I return 6 for foo
? The asynchronous function I am using is actually from a framework, not setTimeout
.
As it stands you cannot make foo
return the value of a
as set within the callback given to setTimeout
because when the return statement is executed the timeout callback function has not been invoked.
What you can do is make your function async
and wrap the call to setTimeout
in a Promise, then await that promise to allow the setTimeout
callback to be invoked, and then finally return a
.
async function foo() {
let a = 5;
await new Promise(resolve => {
setTimeout(function() {
a = 6;
resolve();
}, 1000);
});
return a;
}
(async () => {
console.log("running...")
console.log(await foo());
})()