Last active
July 12, 2020 20:14
-
-
Save paszkowskiDamian/4b61843ca435904519628d585c11ca2d to your computer and use it in GitHub Desktop.
Parallel data fetching
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
/* Parallel fetch | |
* Case: When you need to fetch data from server and | |
* those request does not need data from previous one (they are independent). | |
* Pros: Significantly reduces time to get whole response. | |
*/ | |
type User = {} | |
type Organization = {} | |
declare function fetchUser(name: string): Promise<User> | |
declare function fetchOrganization(name: string): Promise<Organization> | |
async function fetchData(userName: string, organizationName: string) { | |
const user = await fetchUser(userName); // fetches usualy ~300ms; | |
const organization = await fetchUser(organizationName); // fetches usualy ~500ms; | |
return { user, organization }; // Overall fetching time will be ~800ms; | |
} | |
async function fetchData_(userName: string, organizationName: string) { | |
const [user, organization] = await Promise.all([ | |
fetchUser(userName), // fetches usualy ~300ms; | |
fetchUser(organizationName), // fetches usualy ~500ms; | |
]); | |
return { user, organization }; // Overall fetching time will be ~500ms; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment