Xiaofan Guo
Xiaofan Guo

Reputation: 43

Call resolve() explicitly in .then()

If I create a new promise object and return a new promise object inside like this, p1 will keep pending.

var p1 = new Promise((resolve, reject) => {
    return new Promise((resolve, reject) => {
        resolve(1);
    });
});

But if I chain the inner new promise with a then() and call revolve, the outer new promise p1 will get resolved.

var p1 = new Promise((resolve, reject) => {
    return new Promise((resolve, reject) => {
        return resolve(1);
    }).then(data => resolve(123));
});

It seems that the resolve() in the .then() actually resolve p1. Can anyone tell me what is happening here? Why can't the first p1 be resolved and why the second p1 is resolved?

Upvotes: 3

Views: 422

Answers (3)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

The promise p1 in the second snippet gets resolved as the resolve inside the then callback is referring to the resolve passed in the callback of the outer Promise constructor and not to the resolve of the inner Promise constructor.

In the first snippet, the resolve is always referring to the resolve of the inner Promise constructor and hence the outer Promise never gets resolved.

Just rename the callbacks and check:

var p1 = new Promise((outerResolve, reject) => {
  return new Promise((innerResolve, reject) => {
      //resolve of inner
      return innerResolve(1);
    })
    .then(data => {
      console.log(data);
      //Resolve of outer
      outerResolve(123);
    });
});

p1.then(console.log)

The outer promise in the first snippet p1 will never resolve as its resolve is never called. it will always be in the pending state.

Upvotes: 1

fodma1
fodma1

Reputation: 3535

You're shadowing the argument resolve in the first example. Try:

var p1 = new Promise((resolve1, reject1) => {
  resolve1(new Promise((resolve2, reject2) => {
    resolve2(1);
  }));
});

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074445

The return value of the promise executor function (the function you pass to new Promise) is completely ignored; it has no meaning. Returning a promise from it doesn't do anything. Also, as fodma1 points out, you're calling the inner promise's resolve, not the outer one.

Your second form uses a fulfillment handler on the inner promise to fulfill the outer one. While you can do that, and perhaps sometimes it's appropriate, in the usual case you'd just use the inner promise directly and do the other work in the then callback.

Upvotes: 1

Related Questions