So, I was recently introduced to the concept of promises and I was told for chaining purpose, we use ‘then’, which is actually invoked when the attached promise object is fulfilled. And, to do some work after this object is resolved, I can have a callback inside then which again can return promise.
So, if this cb inside ‘then’ function is returning a promise and ‘then’ itself return a promise, so, does it mean the ‘then’ function takes this promise from the cb and directly returns it back as it is.
Here is the code:
let p2;
function firstpromise() {
return new Promise((resolve, reject) => {
setTimeout
(
() => {
console.log("first promise completed");
resolve("first promise resolved");
}, 10000
);
});
}
const p = firstpromise();
const pro = p.then((data) => {
p2 = new Promise((resolve, reject) => {
setTimeout
(
() => {
console.log("second promise completed" + data);
resolve("second promise resolved");
}, 5000
);
});
return p2;
});
console.log(pro === p2);
Both pro and p2 are giving same result on console, once the promise is resolved, so this makes me think that pro and p2 are same.
To simplify my confusion:
when i write fun1(fun2); i am calling fun1 function and passing fun2 in it. now it is upto fun1 if it calls fun2 or not. Suppose fun2 is called and it returned "hello" to fun1. but fun1 may return "bye" to us. So this whole time we were unaware of any value returned by fun2.
so my question is that the function "then" returned a promise, but internally it called secondpromise function which itself "returned promise to then function", so does it mean "then "as it is returned forward the same promise returned to it by second promise function?
Also, console.log(pro===p2); actually prints false.
If anyone can please explain the internal of then in particular, it would be a great help.. 😉
2
Answers
From the documentation of Promise.prototype.then()
Notice that it returns immediately, it doesn’t wait for the callback to return. So unless it can predict the future, it can’t possibly return the same promise that the callback returns.
The promise that it’s equivalent to is the one that it was called on, not the one returned by the callback.
In short, the promise returned from
then()
is not the same promise as the one returned in the callback. When you callthen()
on a promise a new promise is returned immediately, which is resolved (or rejected) after the the callbacks have run.Since the promise are asynchronous, it can’t wait for the callbacks to be processed before returning anything (and if the base promise never resolves, they would never be processed). If that was the case then a chained promise could never act on the result of a previous one (like fetching data from an external source)
Here is an example of what would happen if it needed to wait for the callback.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then