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.
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.