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.. ;)