In our code we end up making a lot of asynchronous, independent calls to 3rd party and internal REST APIs in order to build up among other things, currency conversion rates, Airport IATA Code -> Name mapping and getting a result set for a user's Flights search.
This led to a lot of head-scratching about how to improve speed, we needed all these calls to resolve before we could continue, but because they were all independent did we need to wait for each Promise to resolve before we could invoke another?
In short: no, we could use Promise.all to invoke all our independent asynchronous calls at once, and await them all to have resolved, not worrying about which resolves first:
const [ conversionRates, airports, flights, ] = await Promise.all([ getConversionRates(), getAirports(), getFlights() ]);
Brilliant! We're waiting once, for the longest process to resolve and gathering all out data in one go.
But we still have some synchronous calls later one which again, are independent, non-mutating functional code. Could we do the same thing there?
Yes was the answer, with a bit of fore-thought about grouping functions together and making sure our code was fully functional in design, we are able to use Promise.all to await the results of multiple functions regardless of whether they are defined as
async or not.
- Run groups of them simultaneously using Promise.all
- Await for all the functions to resolve, rather than one at a time