Skip to content

Instantly share code, notes, and snippets.

@thejhh
Last active January 21, 2020 14:51
Show Gist options
  • Select an option

  • Save thejhh/3d14c3bf3e901ec243d4d85fcffceab4 to your computer and use it in GitHub Desktop.

Select an option

Save thejhh/3d14c3bf3e901ec243d4d85fcffceab4 to your computer and use it in GitHub Desktop.
// Original supposedly "correct" way: https://flaviocopes.com/javascript-async-await-array-map/
// NOPE! This is correct:
// Function that returns a promise
const functionWithPromise = item => {
return Promise.resolve('ok');
};
// Prefer functions without side effects. Much easier to understand, unit test, re-use and optimize (eg. three shaking).
const getData = async (list) => {
// Only reason to have another "async" wrapper is if functionWithPromise() might throw something and you want to catch it
// BUT you can inline it, too.
return await Promise.all(list.map( async item => await functionWithPromise(item)) );
};
//
const LIST = [1, 2, 3, 4, 5] //...an array filled with values
getData(LIST).then(data => {
console.log(data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment