Mastering JavaScript Promises

Mastering JavaScript Promises

Mastering JavaScript Promises: Promise.all(), Promise.allSettled(), Promise.any(), and Promise.race() ??


Handling multiple asynchronous operations efficiently is a crucial skill in JavaScript. Let’s dive into four key Promise methods that help manage concurrent async tasks like a pro!


Promise.all()

This method runs multiple promises in parallel and waits for all of them to resolve. If any promise fails, the entire Promise.all() is rejected immediately. It’s best used when all tasks must be completed successfully before proceeding.

const fetchUser = fetch('/user');
const fetchOrders = fetch('/orders');

Promise.all([fetchUser, fetchOrders])
  .then(([userRes, ordersRes]) => Promise.all([userRes.json(), ordersRes.json()]))
  .then(([user, orders]) => console.log(user, orders))
  .catch(error => console.error('One of the requests failed:', error));
        

Promise.allSettled()

Unlike Promise.all(), this method waits for all promises to be completed, regardless of success or failure. It’s useful when you want the result of each task, no matter the outcome.

const fetchUser = fetch('/user');
const fetchOrders = fetch('/orders');
const fetchAnalytics = fetch('/analytics');

Promise.allSettled([fetchUser, fetchOrders, fetchAnalytics])
  .then(results => results.forEach(result => console.log(result.status, result.value || result.reason)));
        

Promise.any()

This one resolves as soon as any of the given promises succeeds. If all fail, it rejects with a AggregateError listing of all failure reasons. It’s great when you need the first successful response.

const api1 = fetch('https://api1.com/data');
const api2 = fetch('https://api2.com/data');
const api3 = fetch('https://api3.com/data');

Promise.any([api1, api2, api3])
  .then(response => response.json())
  .then(data => console.log('First successful response:', data))
  .catch(error => console.error('All requests failed:', error.errors));        

Promise.race()

Returns the result of the first promise to settle, whether it succeeds or fails. Ideal when you only care about the fastest response.

const fetchWithTimeout = (url, timeout) => {
  const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject('Timeout'), timeout));
  return Promise.race([fetch(url), timeoutPromise]);
};

fetchWithTimeout('https://api.example.com/data', 5000)
  .then(response => response.json())
  .then(data => console.log('Received:', data))
  .catch(error => console.error('Request failed or timed out:', error));
        

When to Use What?

Use Promise.all() when all tasks must be completed successfully.

Use Promise.allSettled() when you need results from all tasks, regardless of success/failure.

Use Promise.any() when you need the first successful response.

Use Promise.race() when speed is your priority and you don't care about success/failure.

Mastering these methods can help you write efficient, resilient, and scalable async code!


Mohamed Lotfy ??

Muslim | Software Engineer II at BitBang, LLC.

3 周

Concise summary with examples.

要查看或添加评论,请登录

Padula Guruge的更多文章