Skip to content

Instantly share code, notes, and snippets.

@itaditya
Last active September 30, 2023 06:47
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save itaditya/3f32aa93b874e943c6b9c26a7e9d7e21 to your computer and use it in GitHub Desktop.
Save itaditya/3f32aa93b874e943c6b9c26a7e9d7e21 to your computer and use it in GitHub Desktop.
Snippet for Avoiding the async/await hell medium article
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
@anton-kl
Copy link

Missing closing parenthesis here. Should be:
Promise.all([selectPizza(), selectDrink()]).then(orderItems) // async call
<3

@itaditya
Copy link
Author

Thanks @anton-kl fixed it now

@ATGardner
Copy link

Why not just use

(async () =>{
  await Promise.all([selectPizza(), selectDrink()])
  await orderItems() // can also be return or even without anything, if we want to fire-and-forget
})()

why mix async/await with .then? any special reason?

@orzFly
Copy link

orzFly commented Apr 16, 2018

L24 should be started with await

@itaditya
Copy link
Author

I have updated the gist.

@itaditya
Copy link
Author

why mix async/await with .then? any special reason?

@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 use async/await

@zju0621
Copy link

zju0621 commented Oct 9, 2018

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