Testing Javascript async await not waiting

Viewed 29

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 Answers

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

Related