Skip to content

Instantly share code, notes, and snippets.

@armanozak
Created August 4, 2020 15:54
Show Gist options
  • Save armanozak/3cff615cf96bb85849ee4c9c49f431d2 to your computer and use it in GitHub Desktop.
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
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