Chaining .then() calls in ES6 promises

2019-07-09 08:50发布

问题:

I thought it was supposed to be possible to chain the .then() method when using ES6 Promises. In other words I thought that when a promise is resolved the value passed to the resolve function should be passed to any chained then handlers. If this is so how come value comes back undefined in the chained then handler below?

function createPromise() {
  return new Promise((resolve) => {
    resolve(true);
  });
}

createPromise()
  .then((value) => {
    console.log(value); // expected: true, actual: true
  })
  .then((value) => {
    console.log(value); // expected: true, actual: undefined
  });

回答1:

Each then() can return a value that will be used as the resolved value for the next then() call. In your first then(), you don't return anything, hence value being undefined in the next callback. Return value in the first one to make it available in the second.

function createPromise() {
  return new Promise((resolve) => {
    resolve(true);
  });
}

createPromise()
  .then((value) => {
    console.log(value); // expected: true, actual: true
    return value;
  })
  .then((value) => {
    console.log(value); // expected: true, actual: true
  });



回答2:

You have to return it inside a promise to pass it along. Or create a new promise that resolves with it.

createPromise()
.then((value) => {
    return value;
})
.then((value) => {
    console.log(value);
});

Or

createPromise()
.then((value) => {
    return new Promise.resolve(value);
})
.then((value) => {
    console.log(value);
});


回答3:

.then always returns a Promise that resolves to the value returned in the function callback. Since you return nothing in the first call to .then, undefined becomes the resolved value of the Promise returned.

In other words, if you want to resolve true in the second call to .then, you'll have to return it in the first, like so,

createPromise() // returns a Promise
  .then(function (value) {
    console.log(value); // => true
    return value; // now this will return a Promise that resolves the value `true`
  }).then(function (value) {
    console.log(value) // => true
  });

You can refer to MDN's documentation on method chaining for ES2015 promises if you need further information.