Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Use `Promise.any()` for the First Successful Result

1 min read .
Use `Promise.any()` for the First Successful Result

Promise.any() fulfills as soon as one input promise fulfills. Rejections are ignored until either a promise succeeds or every input promise has rejected.

const first = Promise.reject(new Error('first failed'));
const second = new Promise((resolve) => setTimeout(resolve, 100, 'second succeeded'));
const third = new Promise((resolve) => setTimeout(resolve, 200, 'third succeeded'));

console.log(await Promise.any([first, second, third]));
// second succeeded

When Everything Fails

If every promise rejects, Promise.any() rejects with an AggregateError:

try {
  await Promise.any([
    Promise.reject(new Error('A')),
    Promise.reject(new Error('B')),
  ]);
} catch (error) {
  console.error(error.errors);
}

HTTP Requests Need Explicit Status Validation

fetch() fulfills even for HTTP responses such as 404 and 500, so wrap requests when “success” means a 2xx response:

async function fetchOK(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`${url}: HTTP ${response.status}`);
  }
  return response;
}

const response = await Promise.any(urls.map(fetchOK));

Promise.any() vs. Promise.race()

Promise.race() settles on the first promise to settle, including a rejection. Promise.any() waits for the first fulfillment.

Conclusion

Use Promise.any() when several independent sources can satisfy the same need and the first successful result is enough. Handle AggregateError for the all-failed case and define what “success” means for APIs such as fetch().

Related Posts

chevron-up