1

How to wait for setTimeout to complete first

function a() {
  setTimeout(() => {
    console.log('should wait');
  }, 5000);
}
async function b(c) {
  console.log('hello');
  await c();
}
b(a);
console.log('out');
My expected output is

Hello

should wait

out

Vivek Modi
  • 31
  • 1
  • 9
  • 1
    setTimeout does not use promises. – Evert Apr 03 '21 at 06:54
  • `setTimeout` is asynchronous. Other code will run while the timeout "waits" to execute the callback you pass to it – blex Apr 03 '21 at 06:55
  • https://stackoverflow.com/questions/49813405/async-await-function-does-not-wait-for-settimeout-to-finish – TechySharnav Apr 03 '21 at 06:58
  • 2
    Does this answer your question? [async/await function does not wait for setTimeout to finish](https://stackoverflow.com/questions/49813405/async-await-function-does-not-wait-for-settimeout-to-finish) – nyedidikeke Apr 03 '21 at 07:00

2 Answers2

4

setTimeout does not return a Promise and await only works with Promises.

Also, put the console.log("out") inside the b function for it to run after the a function.

Check the code snippet below, it does what you were looking for.

function a() {
  return new Promise((res, rej) => {
    setTimeout(() => {
      console.log('should wait');
      res();
    }, 5000);
  })
}
async function b(c) {
  console.log('hello');
  await c();
  console.log('out');
}
b(a);
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
0

A function must return a promise if you want example to work properly (await keywords "awaits" for returned promise to resolve): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

You example should look like:

function a() {
  return new Promise(resolve => {
    setTimeout(resolve, 5000);
  });
}

async function b(c) {
  console.log('hello');
  await c();
  console.log('should wait');
}
await b(a);
console.log('out');

Note that you can use await keyword on function, because declaring function as async automatically makes it return a promise.

blex
  • 24,941
  • 5
  • 39
  • 72
Furman
  • 2,017
  • 3
  • 25
  • 43