Created
May 28, 2021 18:38
-
-
Save SmolinPavel/0ca82ee6a0767bdaa892d2570ac9c239 to your computer and use it in GitHub Desktop.
Compare Promise.all calls with .then vs async/await
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
/* | |
PROMISE/THEN approach | |
*/ | |
const userIds = [1, 2, 3]; | |
const requests = userIds.map((userId) => | |
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`), | |
); | |
Promise.all(requests) | |
.then((responsesArr) => { | |
const promiseArr = responsesArr.map((response) => response.json()); | |
return Promise.all(promiseArr); | |
}) | |
.then((resultsArr) => { | |
resultsArr.forEach((result) => { | |
console(`user!!!`, result.name); | |
}); | |
}) | |
.catch(() => console.log('Something went wrong...')); | |
/* | |
ASYNC/AWAIT approach | |
*/ | |
async function fetchUsers(count) { | |
const userIds = new Array(count).fill(null).map((_, idx) => idx + 1); | |
try { | |
const requests = userIds.map((userId) => | |
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`), | |
); | |
const responsesArr = await Promise.all(requests); | |
const promiseArr = responsesArr.map((response) => response.json()); | |
const resultsArr = await Promise.all(promiseArr); | |
resultsArr.forEach((result) => { | |
console.log(`user!!!`, result.name); | |
}); | |
} catch (err) { | |
console.log(err); | |
} | |
} | |
fetchUsers(7); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment