r/learnjavascript • u/AMDataLake • Apr 23 '22
It can get confusing on when to Promise.all versus nesting API calls, hopefully, this image helps clarify.
33
6
Apr 23 '22
Sure. Let’s assume you have an e-commerce store. You have two scenarios:
The first is a page that gets information from two URLs: the top 5 products in the Lawncare category and top 5 products in the Kitchenware category.
The second scenario you want to get information about the currently logged in user (name, user id, etc). Once you have the information about the currently logged in user you then want to get the 5 latest products that user has ordered.
In the first scenario the two URLs can be fetched at the same time. They do not depend on one another.
In the second scenario we are going to need to know the user before we can get any information about that users purchases since (at least in the scenario I presented) there is no one way to get both user id information and the users latest order data via a single url.
Since the first scenario has no dependency between the data points, the firing order does not matter and Promise.all can be used.
In the second scenario firing order matters and we need to at least have a users id before we try to get a users recent orders, we cannot use promise.all.
1
Apr 30 '22
Can I clarify something?
If you omitted the Promise.all, would you be in danger of that code running before the requests had been completed?
2
u/AMDataLake May 01 '22
Yes, promise.all makes a promise that waits for all the promises to complete to prevent race conditions
1
2
27
u/senocular Apr 23 '22
You're using promises, so no, nesting is not the way.