0

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
0

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.