skip to Main Content

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


  1. From the documentation of Promise.prototype.then()

    The then() method of Promise instances takes up to two arguments: callback functions for the fulfilled and rejected cases of the Promise. It immediately returns an equivalent Promise object, allowing you to chain calls to other promise methods.

    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.

    Login or Signup to reply.
  2. In short, the promise returned from then() is not the same promise as the one returned in the callback. When you call then() 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.

    // Fetch returns a promise which will resolve when the request is done
    const promise1 = fetch('example.com');
    
    // Adding another promise to the chain with .then() is simply saying
    // "when the previous promise resolves, do this next". In this case the
    // next thing would be to parse the result as json. Since this callback
    // depends on the response from fetch, it can't be called until the response
    // is available.
    // response.json() in turn returns a new promise (much like in your example)
    // which will resolve when the json is fully loaded and parsed.
    const promise2 = promise1.then(response => response.json());
    
    // when the data has been parsed, maybe we process it or log it or something
    const promise3 = promise2.then(data => { /* Process data */ });
    
    // Logging promise3 here will show a pending promise, which is waiting
    // for all the previous promises to execute since it is part of the "chain"
    // and when we get here "fetch" is most likely just starting the request
    // and no callbacks will have been called yet, but we still have a promise
    // of a future resolt of some sort.
    console.log(promise3);
    

    Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search