JavaScript Promises: All, AllSettled, Any, Race, and Concurrency Patterns
Promises are central to modern JavaScript, but most developers use only the basics. Firefox fully implements the Promise specification and the full Promise static API. This guide covers practical patterns: error handling, concurrency control, cancellation, and the less-used Promise methods. Promise Fundamentals Recap // Creating a Promise const p = new Promise (( resolve , reject ) => { // Async…
JavaScript Promises are a fundamental concept in modern JavaScript, yet many developers only utilize the basics. Firefox provides a full implementation of the Promise specification along with the complete Promise static API. This guide explores practical patterns such as error handling, concurrency control, cancellation, and delves into less commonly used Promise methods.
To recap, creating a Promise involves using the constructor `new Promise()` with a callback function that takes `resolve` and `reject` functions. The asynchronous operation is performed inside this callback, and `resolve` is called with a value upon success, while `reject` is invoked with an Error object if the operation fails. Consuming the Promise can be done using `then()` for successful outcomes, `catch()` for handling errors, and `finally()` for cleanup tasks.
The `Promise.all`, `Promise.allSettled`, `Promise.any`, and `Promise.race` methods provide various ways to handle multiple promises concurrently. `Promise.all` waits for all promises to resolve successfully, returning an array of their results in order. It should be used when all requests must succeed. `Promise.allSettled`, on the other hand, waits for all promises to settle (either successfully or unsuccessfully) and returns an array of objects with `status` (either 'fulfilled' or 'rejected') and either a `value` or `reason`.
This method is useful when some requests can fail, but you still want all results. `Promise.any` returns the first promise that resolves successfully, ignoring the rest. It's ideal for trying multiple sources and using the first available response. Lastly, `Promise.race` returns the first promise to settle (either successfully or unsuccessfully), making it suitable for timeout patterns where you need to prevent long-running operations.
Managing controlled concurrency is crucial to avoid overwhelming systems with too many simultaneous requests. An example provided demonstrates an `async` function `mapWithConcurrency` that processes an array of items with an asynchronous function but limits the number of concurrent operations to a specified concurrency level (default is 5). It maintains an array of results and uses a worker function to run asynchronous tasks in parallel, ensuring that no more than the specified concurrency level of tasks execute at once.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.