Search⌘ K
AI Features

Return Promises in Promise Chains

Explore how to return promises within promise chains to handle sequential asynchronous operations in JavaScript. Understand how this technique allows passing data and errors through the chain, making code cleaner and easier to manage. Gain insight into attaching rejection handlers and chaining multiple async steps efficiently.

Returning promises in promise chains

Returning primitive values from promise handlers allows the passing of data between promises, but what if we return an object? If the object is a promise, then there’s an extra step that’s taken to determine how to proceed. Consider the following example:

Javascript (babel-node)
const promise1 = Promise.resolve(11);
const promise2 = Promise.resolve(22);
promise1.then(value => {
console.log(value); // 11
return promise2;
}).then(value => {
console.log(value); // 22
});

In this code, promise1 resolves to 11. The fulfillment handler for promise1 returns promise2, a promise already in the resolved state. The second fulfillment ...