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
1
  • 2
    Because setTimeout() isn't an async function. For await to work the method you call needs to return a promise. Commented Sep 18, 2022 at 16:16

1 Answer 1

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();

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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...
Please accept the answer as the solution if the problem is solved

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.