Reputation: 36580
Doing some research about Promises
and I know that a Promise
object can be in three states (pending, resolved, rejected). The logic responsible for each of these three states is in a callback function which gets passed into the Promise
constructor. This callback function has 2 functions as its arguments resolve and reject which are called when this callback either results in success or failure.
After the Promise
is instantiated we can then add response handler callbacks to the promise by calling the .then
function on it. The .then
function takes 2 callback functions as its arguments. The first argument is the callback function is called in case the Promise
resolve function is called and the second callback is called in case the Promise
reject function is called. You can also call .catch
on Promises
to handle the rejected promises although this is just syntactic sugar for:
.then(undefined, () => { failure callback})
What I find harder to understand is the fact that the .then
method returns a Promise
. For example in the following code:
let random = (Math.random() * 10);
let promise = new Promise((res, rej) => {
if (random >= 5) {
res(random);
}
rej(random);
});
promise
.then(
(nr) => {
console.log("succes: " + nr);
return nr + 5;
})
.then((nr) => {
console.log(nr);
})
.catch(
(nr) => {
console.log("failure: " + nr);
})
In the example at the first .then
it returns : nr + 5
. In resolve cases of the Promise
this value is succesfully passed onto the second .then
. How is this possible? Is it under the hood:
return new Promise((res,rej) => {
res(nr + 5)
})
or is this caused by something else?
Upvotes: 4
Views: 15639
Reputation: 33726
Look at this: Promises chaining
Normally, a value returned by a .then handler is immediately passed to the next handler. But there’s an exception.
If the returned value is a promise, then the further execution is suspended until it settles. After that, the result of that promise is given to the next .then handler.
Basically, when you return a value, i.e: (nr + 5) or 5 or [1, 2] or {a: 1}
, Etc., that value is passed immediately to the next handler (.then).
Upvotes: 3
Reputation: 664247
Yes, this one of major features of promises: they are chainable.
The then
method does return a new promise that will be resolved with the result of the callback. It does indeed construct a new Promise
and does call resolve
with the return value when the callback will be called.
You might want to take a look at this toy implementation to see how it is implemented (without the error handling, though).
Upvotes: 5
Reputation: 701
It is the behaviour of a promise, it is described here
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
In Return value section:
if the handler function returns a value, the promise returned by
then
gets resolved with the returned value as its value;
Upvotes: 5