Skip to content

Instantly share code, notes, and snippets.

@itaditya
Last active June 1, 2020 07:13
Show Gist options
  • Save itaditya/bd7a0652ba0fa11ef5b6e60922fa156a to your computer and use it in GitHub Desktop.
Save itaditya/bd7a0652ba0fa11ef5b6e60922fa156a to your computer and use it in GitHub Desktop.
Snippet for Avoiding the async/await hell medium article
async function orderItems() {
const items = await getCartItems() // async call
const noOfItems = items.length
const promises = []
for(var i = 0; i < noOfItems; i++) {
const orderPromise = sendRequest(items[i]) // async call
promises.push(orderPromise) // sync call
}
await Promise.all(promises) // async call
}
// Although I prefer it this way
async function orderItems() {
const items = await getCartItems() // async call
const promises = items.map((item) => sendRequest(item))
await Promise.all(promises) // async call
}
@BenjaminVanRyseghem
Copy link

async function orderItems() {
  const items = await getCartItems()    // async call
  const promises = items.map((item) => sendRequest(item))
  await Promise.all(promises)    // async call
}

why not this version instead?
If it's to emphasize the sync/async parts, maybe it's worth mentioning that the code can be simplified 😄

@itaditya
Copy link
Author

itaditya commented Apr 25, 2018

Thanks I have updated the gist. However as many devs mentioned on medium, this method has certain disadvantages like if the number of items is way too large, we'll incur huge cost for context switching

@JonathanLoscalzo
Copy link

this is a cool solution @itaditya, I'm going to fork this gist!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment