-1

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.

Leponzo
  • 624
  • 1
  • 8
  • 20
  • That dupe is 90% relevant. They're using AJAX there, but the same answer applies regardless. – Carcigenicate Feb 19 '20 at 16:09
  • make a promise of it and use `async/await` – Muhammad Usman Feb 19 '20 at 16:09
  • Would you mind answering it in code? I'm a beginner in JS. The other links I saw are too long. – Leponzo Feb 19 '20 at 16:19
  • I don't think you can. `console.log` is synchronous and _will_ log something immediately. It can't be delayed. Even by using `async/await`, it won't wait 1000ms before logging the value you're expecting. You can, however, log the value after it is changed from within the function. – Jeremy Thille Feb 19 '20 at 16:34
  • @JeremyThille It's my bad. I don't need `console.log`, just the `return` value. I had added it here so it would display something when run. – Leponzo Feb 19 '20 at 16:43
  • The answer depends on the actual call. If it does not allow promises/async/await, there is not much you can do with that call. There might be other work arounds, but it all depends on the actual call. So the answer is dependent on the actual code. if it is not setTimeout, what is it exactly. – epascarello Feb 19 '20 at 16:48

1 Answers1

1

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());
})()
sdgluck
  • 24,894
  • 8
  • 75
  • 90