Chaining .then() calls in ES6 promises

家住魔仙堡 提交于 2019-12-11 01:53:51

问题


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.



来源:https://stackoverflow.com/questions/41556251/chaining-then-calls-in-es6-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!