Member-only story
As developers, we frequently encounter situations requiring coordination between multiple asynchronous tasks. When faced with such challenges, understanding how to compose promises proves vital for crafting maintainable and scalable codebases.
In this tutorial, we delve into several popular techniques for composing promises, accompanied by concrete examples and insights.
Sequential Execution
Compose promises sequentially when each task depends on the outcome of its predecessors. Implement this pattern via the reduce()
array method, iteratively invoking each promise in sequence and accumulating results.
Suppose you need to perform some API requests serially, manipulating responses stepwise. Here’s an illustrative example:
const urls = ['https://api.example.com/step1', 'https://api.example.com/step2'];
urls
.reduce((accumulator, currentUrl) => {
return accumulator.then(previousResult =>
fetch(currentUrl).then(response => response.json()).then(currentResult => ({ ...previousResult, ...currentResult })))
);
}, Promise.resolve({}))…