Home > database >  Typescript - unexpected sequence with setTimeout in combination with async and await
Typescript - unexpected sequence with setTimeout in combination with async and await

Time:10-22

When I run this script, the output is different from what I expect: 1 through 4. Why is that?

const delay2 = async ( ms: number) => setTimeout( () => {
  console.log( '2 - timeout')
}, ms);

const mainAsync2 = async () => {
  console.log( '1 - before');
  await delay2( 2000);
  console.log( '3 - after');
}
mainAsync2()
.then( res => console.log( '4 - done'));

The output is:

1 - before
3 - after
4 - done
2 - timeout

CodePudding user response:

setTimeout by itself does not return a promise, so awaiting it does nothing. It simply sets a timeout for ms milliseconds. Instead, you should make your delay2 return a promise that resolves after ms milliseconds, for example:

const delay2 = async (ms: number) =>
    new Promise(res => setTimeout(() => { 
        console.log('2 - timeout');
        res();
    }, ms));
  • Related