简体   繁体   中英

Chaining .then() calls in ES6 promises

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM