Created
July 10, 2021 10:16
-
-
Save damarowen/6321f6529be367f669cce13222efada8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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