Skip to content

Instantly share code, notes, and snippets.

@damarowen
Created July 10, 2021 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damarowen/6321f6529be367f669cce13222efada8 to your computer and use it in GitHub Desktop.
Save damarowen/6321f6529be367f669cce13222efada8 to your computer and use it in GitHub Desktop.
Why would you use this?
Promise.any() lets you run a list of promises
Concurrently, ignoring any that reject unless all of the promises reject
Promise.any([
fetch("https://google.com/").then(() => "google"),
fetch("https://apple.com").then(() => "apple"),
fetch("https://microsoft.com").then(() => "microsoft"),
])
.then((first) => {
// Any of the promises was fulfilled.
console.log(first);
})
.catch((error) => {
// All of the promises were rejected.
console.log(error);
});
Promise.race() also takes an array of promises, but it fulfills or rejects as soon as any one of the promises fulfills or rejects.
import getBlogPost from "./utils/getBlogPost";
const wait = (time) => new Promise((resolve) => setTimeout(resolve, time));
Promise.race([
getBlogPost(1),
wait(1000).then(() => Promise.reject("Request timed out")),
])
.then(([blogPost]) => {
// If getBlogPost fulfilled first, we'll get it here
})
.catch((error) => {
// If the request timed out, the `Promise.reject` call
// above will cause this catch block to execute
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment