Created
June 21, 2022 01:10
-
-
Save hadnazzar/57420e0c3470f5b364a4a59072ab3895 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 await data.json() | |
} | |
const userIdsToFetch = [1,2]; | |
const fetchTodosById = async (id) => { | |
const data = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`) | |
return await data.json() | |
} | |
const todoIdsToFetch = [6,7]; | |
const promisesToFetch = [ | |
...userIdsToFetch.map(userId => fetchUserDetailsById(userId)), | |
...todoIdsToFetch.map(todoId => fetchTodosById(todoId)), | |
] | |
const getDataParallel = async () => { | |
console.time('getDataAsync') | |
try { | |
const data = await Promise.all(promisesToFetch) | |
data.forEach((el) => console.log(el)) | |
} catch (error) { | |
console.log(`Error: ${error}`) | |
} | |
console.timeEnd('getDataAsync') | |
} | |
getDataParallel() | |
const getDataOneByOne = async () => { | |
console.time('getDataOneByOne') | |
try { | |
const user1 = await fetchUserDetailsById(1) | |
const user2 = await fetchUserDetailsById(2) | |
const todo1 = await fetchTodosById(1) | |
const todo2 = await fetchTodosById(2) | |
} catch (error) { | |
console.log(`Error: ${error}`) | |
} | |
console.timeEnd('getDataOneByOne') | |
} | |
getDataOneByOne() | |
/* | |
{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} | |
getDataAsync: 237.945068359375 ms | |
getDataAsync: 237.954ms | |
getDataOneByOne: 655.406005859375 ms | |
getDataOneByOne: 655.506ms | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment