Home > Software engineering >  JS - Why code does not run after async / await for promise
JS - Why code does not run after async / await for promise

Time:01-23

I have a sample code on TS playground represents my problem. In an async function, I log the result after await for the promise, but only the code inside promise run, not the log outside of it. Could someone explain this problem?

Here is the code:

const asyncFnc = async () => {
    let result = false;
    await new Promise(resolve => {
        setTimeout(() => {
            // This log worked
            console.log('waited 5s');
            result = true;
        }, 5000);
    });
    // This log did not worked
    console.log(result);
}

asyncFnc();

And the result: enter image description here

CodePudding user response:

You need to call resolve() in your timeout

CodePudding user response:

await sends the parent function to sleep until the promise on the right hand side settles (i.e. resolves or rejects).

Your promise never resolves or rejects. (i.e. you don't call resolve, make use of the second argument, or throw an exception).

Thus the parent function sleeps forever.


The idiomatic way to write this would be to avoid setting variables in the wider scope as a side effect, and just resolve with the values instead.

const asyncFnc = async () => {
    const result = await new Promise(resolve => {
        setTimeout(() => {
            console.log('waited 5s');
            resolve(true);
        }, 5000);
    });
    console.log(result);
}

asyncFnc();

  • Related