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