Last active
June 21, 2022 00:43
-
-
Save hadnazzar/558621360ce2925d601d6327e6e712fb 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
import fetch from 'node-fetch'; | |
const fetchUserDetailsById = async (id) => { | |
const data = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`); | |
return data.json(); | |
}; | |
const userIdsToFetch = [1, 2]; | |
const fetchTodosById = async (id) => { | |
const data = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`); | |
return data.json(); | |
}; | |
const todoIdsToFetch = [6, 7]; | |
const promisesToFetch = [ | |
...userIdsToFetch.map((userId) => fetchUserDetailsById(userId)), | |
...todoIdsToFetch.map((todoId) => fetchTodosById(todoId)), | |
]; | |
const getData = async () => { | |
try { | |
const data = await Promise.all(promisesToFetch); | |
data.forEach((el) => console.log(el)); | |
} catch (error) { | |
console.log(`Catch block, Error: ${error}`); | |
} | |
}; | |
getData(); | |
/* | |
{id: 1, name: 'Leanne Graham', username: 'Bret', email: 'Sincere@april.biz', address: {…}, …} | |
{id: 2, name: 'Ervin Howell', username: 'Antonette', email: 'Shanna@melissa.tv', address: {…}, …} | |
{userId: 1, id: 6, title: 'qui ullam ratione quibusdam voluptatem quia omnis', completed: false} | |
{userId: 1, id: 7, title: 'illo expedita consequatur quia in', completed: false} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment