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 Promise treat the resolve function as returning a falsey value?

The following code

new Promise((resolve) => {
    const v = resolve("called resolve()");
    if (!v) {
        console.log("resolve() returned a falsey value");
    }
}).then((value) => {
    console.log(value);
    return true;
});

outputs

resolve() returned a falsey value
called resolve()

Why did the if statement in the Promise’s function body get executed even though the provided resolve function through .then() clearly returns true?

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

Also the if statement is clearly written after the resolve function call, why does it get executed before it finds out what the resolve function actually returns?

>Solution :

That’s how it is designed: it returns undefined, always. The purpose of the resolve function is to set the promise’s state to resolved, nothing more. There’s no need to return a value, since there’s no information that can be provided back to you. If you care about what you resolved it with (in your case, "called resolve()"), you can save that in a variable and use it.

const value = "called resolve()"
resolve(value);
if (!value) {
  // ...
}

Why did the if statement in the Promise’s function body get executed even though the provided resolve function through .then() clearly returns true?

The resolve function just deals with this promise; the one that’s created by new Promise. It doesn’t know anything about other promises, such as the one created by calling .then on this promise. Even if it did know about the other promises, it needs to return a value right now, and those other promises havn’t resolved yet.

Also the if statement is clearly written after the resolve function call, why does it get executed before it finds out what the resolve function actually returns?

When you call resolve, you set the state of the promise to resolved, and then immediately move on to the next line of code. If there are any pieces of code that have called .then on your promise, they will get queued up to execute, but they don’t execute yet. Your synchronous code must first return, and only then does the .then callback execute.

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