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.
2
Answers
Because your promise executor is not calling the
resolve
function that you’re expected to call when a promise you create withnew Promise
should be resolved.In other words, your
should be
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 ofnew 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.use this method