Created
August 4, 2020 15:54
-
-
Save armanozak/3cff615cf96bb85849ee4c9c49f431d2 to your computer and use it in GitHub Desktop.
[Promise.all vs Promise.any vs Promise.race] How to Combine Promises #tip #javascript
This file contains hidden or 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
const apiUrl = 'https://jsonplaceholder.typicode.com'; | |
const createUserEndpoint = userId => apiUrl + '/users/' + userId; | |
const createTodosEndpoint = userId => createUserEndpoint(userId) + '/todos'; | |
const createAltTodosEndpoint = userId => apiUrl + '/todos?userId=' + userId; | |
const createTimeout = seconds => new Promise( | |
(_, reject) => setTimeout(() => reject('TIMEOUT'), seconds * 1000) | |
); | |
const fetchJSON = endpoint => fetch(endpoint).then(res => res.json()); | |
/** | |
* Promise.all | |
* `<state>` will be "fulfilled" when all promises resolve. -> then | |
* `<state>` will be "rejected" when any promise rejects. -> catch | |
*/ | |
Promise.all([ | |
fetchJSON(createUserEndpoint(1)), | |
fetchJSON(createTodosEndpoint(1)) | |
]) | |
.then(([user, todos]) => ({...user, todos})) | |
.then(console.log) | |
.catch(console.error); | |
/** | |
* Promise.any | |
* `<state>` will be "fulfilled" when any promise resolves. -> then | |
* `<state>` will be "rejected" when all promises reject. -> catch | |
*/ | |
Promise.any([ | |
fetchJSON(createTodosEndpoint(2)), | |
fetchJSON(createAltTodosEndpoint(2)) | |
]) | |
.then(console.log) | |
.catch(console.error); | |
/** | |
* Promise.race | |
* `<state>` will be "fulfilled" when any promise resolves. -> then | |
* `<state>` will be "rejected" when any promise rejects. -> catch | |
*/ | |
Promise.race([ | |
fetchJSON(createUserEndpoint(3)), | |
createTimeout(5) // will reject in 5s | |
]) | |
.then(console.log) | |
.catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment