Published 2021-09-30
Today I will talk about the good time to use Promise.all()
.
As you might have known, we could use Promise.all()
to run multiple async operations concurrently. Let me elaborate some characteristics about Promise.all
:
The above points leads to:
Next, we will real code example on how some good time to use Promise.all
Below scenario is a series of validation to check when sending withdrawal request to backed and we need to query database to get this information.
👎 example. This example was not optimized because we get the balance 1st, then only proceed to retrieve the conversion rate.
// Check has balance
const balance = await transactionService.getBalance()
// Get conversion rates
const conversionRate = await conversionRatesService.getConversionRates()
👍 example. Good example is we could optimized them and call them concurrently.
// Check has balance
const [balance, conversionRate] = await Promise.all([
transactionService.getBalance(),
conversionRatesService.getConversionRates(),
])