Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this async js function not print done

Consider the following script:

async function fn() {
    await new Promise(() => { console.log("promise"); });
    console.log("done");
}
fn();

The output is

promise

If I don’t await the promise then the result differs.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

async function fn() {
    new Promise(() => { console.log("promise"); });
    console.log("done");
}
fn();

The output now is more along the expected lines.

promise
done

I am assuming this is coming from wrong usage of the language somehow but I would like to know the reason for this difference.

>Solution :

Because your promise executor is not calling the resolve function that you’re expected to call when a promise you create with new Promise should be resolved.

In other words, your

async function fn() {
    await new Promise(() => { console.log("promise"); });
    console.log("done");
}
fn();

should be

async function fn() {
    await new Promise((resolve) => { console.log("promise"); resolve(); });
    console.log("done");
}
fn();

if you ever expect it to finish; if you don’t call resolve, the runtime can’t know when the promise has finished (and since the idea of new Promise is to wrap callback-based APIs, it’s not enough to just consider the executor function returning having resolved the promise).

If you don’t await for the promise, it will run (since promises start running immediately, not only when awaited), but it too will have never actually resolved.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading