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