1

Why is it not waiting?

const wrapper = async () => {
  console.log('start');
  await setTimeout(async () => console.log('callback'),5000)
  console.log('end');
}

wrapper();

Result:

start
end
callback

Expected result:

start
callback
end
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Apollon16
  • 36
  • 3

1 Answers1

2

You can use a Promise to wait:

const wait = () => new Promise(resolve => {
  setTimeout(() => { console.log('callback'); resolve(); }, 5000)
});
const wrapper = async () => {
  console.log('start');
  await wait();
  console.log('end');
}

wrapper();
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • Thank you. I also thought of an explanation.: await is only waiting for the **callback to be registered**. Not waiting for execution of the callback. – Apollon16 Sep 18 '22 at 16:40
  • As mentioned above, since `setTimeout` is not async, await will not work as you used it. Wrapping it in a promise which resolves when the timer ends is the right way to do it as await works fine with the promise... – Majed Badawi Sep 18 '22 at 16:53
  • Please accept the answer as the solution if the problem is solved – Majed Badawi Sep 18 '22 at 16:53