Callback best practices
Now that you’ve encountered your first example of callback hell, you know what to avoid. But managing asynchronous code comes with more challenges than just preventing deeply nested callbacks. In fact, there are many situations where controlling the flow of multiple asynchronous tasks requires specific patterns and techniques, especially if you’re working with plain JavaScript without any external libraries.
For example, consider the common scenario where you have an array of URLs and you need to fetch the content of each URL in sequence, one after the other. In real life, one reason why you might want to do something like this sequentially could be due to rate-limiting restrictions (and prevent doing more than one request at the time). To solve this problem, you might be tempted to use a simple forEach()
loop, like the following:
const urls = ['url1', 'url2', 'url3']
urls.forEach(url => {
fetch(url,...