Last active
September 30, 2023 06:47
-
-
Save itaditya/3f32aa93b874e943c6b9c26a7e9d7e21 to your computer and use it in GitHub Desktop.
Snippet for Avoiding the async/await hell medium article
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
async function selectPizza() { | |
const pizzaData = await getPizzaData() // async call | |
const chosenPizza = choosePizza() // sync call | |
await addPizzaToCart(chosenPizza) // async call | |
} | |
async function selectDrink() { | |
const drinkData = await getDrinkData() // async call | |
const chosenDrink = chooseDrink() // sync call | |
await addDrinkToCart(chosenDrink) // async call | |
} | |
(async () => { | |
const pizzaPromise = selectPizza() | |
const drinkPromise = selectDrink() | |
await pizzaPromise | |
await drinkPromise | |
orderItems() // async call | |
})() | |
// Although I prefer it this way | |
Promise.all([selectPizza(), selectDrink()]).then(orderItems) // async call |
The last statement should be
return orderItems();
if, say it returns a order number in Promise?
Even it does not explicitly return a value, there is a Promise created can be used for the return of outer async ().
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@ATGardner if we use await then the code following the
Promise.all
statement will have to wait for the function calls. Why do it when you have a much shorter syntax and which doesn't have a side effect.I believe we should use
.then()
first and if we intentionally want to wait in the entire function then useasync/await