Skip to content

Instantly share code, notes, and snippets.

@merin83
Last active March 20, 2019 20:44
Show Gist options
  • Save merin83/c025233fe767dd8a11775b3a8f44c5e4 to your computer and use it in GitHub Desktop.
Save merin83/c025233fe767dd8a11775b3a8f44c5e4 to your computer and use it in GitHub Desktop.
async/await inside of a loop

When you need it:

To use async/await usually doesn't work in a forEach loop, you need to use a for...of loop instead, or await Promise.all, to actually run async code in parallel.

1. Using for...of loop:

example one:

for async(let item of items) {
  await doSomethingWith(item)
}

example two:

const promises = [1, 2, 3].map(n => Promise.resolve(n*1000))  // 1
const promisesPromise = Promise.resolve(promises)             // 2

// you can't do async at the toplevel, so we need to put it in an iife***(Immediately Invoked Function Expression https://dev.to/gyi2521/what-is-iife-in-javascript-o81) 
void async function() {
  console.log("===== for-of =====")
  //    1                   2
  for await (const val of await promisesPromise)
    console.log(val)

  console.log("===== forEach =====")
  ;(await promisesPromise)                        // wait for 2
    .forEach(async val => console.log(await val)) // wait for 1
}()

1. Using Promise.all():

example one:

check the below screenshot
https://cl.ly/70a80d88dd7d

or follow this code,

const promises = transactionsData.map(async trans => {
	const { destination } = trans;
	const destinationUser = await fetch(`/api/v1/users/${destination}`);
	const destinationUserData = await destinationUser.json();
	return {
		...trans,
		destinationName: destinationUserData.user.full_name
	};
});

const finalTransactions = await Promise.all(promises);

NB: Promise.all() has one drawback - it handles all promises simultaneously which sometimes may not be the best thing. p-all is something which gives a bit of control (via concurrency option) over this.

https://t.co/cy18Ptgar8

some cool promise stuff

https://github.com/sindresorhus/promise-fun

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