|
|
|
|
|
by chncdcksn
3998 days ago
|
|
.then() does create a new promise. Return Promise.reject() in the fulfillment function to reject the new promise. somethingThatReturnsPromiseWithoutError()
.then((res) => {
return Promise.reject("some error");
})
.catch((err) => {
console.log(err); // => some error
});
Promise.resolve() and Promise.reject() return a promise resolved or rejected to the value passed in the first argument. Returning a promise in the fulfillment function passed to .then() chains the promises together. somethingThatReturnsPromise()
.then((foo) => {
return foo.bar;
// Or if you like it more verbose
return Promise.resolve(foo.bar);
// Or pass bar to a function modifying bar that returns a promise
return modifyBarReturnPromise(foo.bar);
})
.then((newBar) => {
console.log(newBar);
});
In your case, if you need step1Val in next promise chain, I personally do this, however people more familiar with promises may know of a better way to do it (maybe with something like Promise.all() or Promise.props() in the BlueBird library). somethingThatReturnsPromise()
.then((first) => {
doSomethingWithFirstAndReturnPromise(first)
.then((second) => {
console.log(first + second);
});
});
|
|
then() returns a new promise resolved to the return value of the function. However, if that value is itself a promise, then it follows the promise chain and passes the eventual state to the next then()/catch() call.