Last active
January 21, 2020 14:51
-
-
Save thejhh/3d14c3bf3e901ec243d4d85fcffceab4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // 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