I do not understand why do we need to write a return?
Because if you don't, the fulfillment callback's return value will be undefined
, as with any other function, which means that the fulfillment value of the promise created by that then
call will be undefined
instead of being result
.
There's no reason for that fulfillment handler at all, it doesn't do anything useful, it just introduces an extra async "tick" into the promise fulfillment. Just remove it:
f().then(result => console.log(result))
In a comment you've said:
I understand that the part was not needed at all to be added. but I added it to understand Promises and in principle it should work, in my opinion.
It's for the reason I mentioned in the first paragraph above: otherwise, the function returns undefined
(implicitly). It's the difference between a
and b
in the following. You might be thinking of concise arrow syntax where the body of the function is just an expression and the return
is implicit, like c
below:
const a = () => {
42;
};
const b = () => {
return 42;
};
const c = () => 42; // No `{` just after the `=>`
console.log(a()); // undefined
console.log(b()); // 42
console.log(c()); // 42
In that case, you'd use:
f().then(result => result) // If you want that there to understand it better
.then(result => console.log(result))
Note there's no Promise.resolve
there. There's no reason to create another promise; the return value of the fulfillment handler will be used to resolve the promise then
returned. No need for an extra one.