Skip to content

Instantly share code, notes, and snippets.

@paszkowskiDamian
Last active July 12, 2020 20:14
Show Gist options
  • Save paszkowskiDamian/4b61843ca435904519628d585c11ca2d to your computer and use it in GitHub Desktop.
Save paszkowskiDamian/4b61843ca435904519628d585c11ca2d to your computer and use it in GitHub Desktop.
Parallel data fetching
/* 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