Guest User

Untitled

a guest
Jun 21st, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. # Async / Await
  2.  
  3. ## Iterating
  4.  
  5. If you want to read the files in sequence, you cannot use forEach indeed. Just use a modern for … of loop instead, in which await will work as expected:
  6.  
  7. ```javascript
  8. async function printFiles () {
  9. const files = await getFilePaths();
  10.  
  11. for (let file of files) {
  12. const contents = await fs.readFile(file, 'utf8');
  13. console.log(contents);
  14. }
  15. }
  16. ```
  17.  
  18. If you want to read the files in parallel, you cannot use forEach indeed. Each of the async callback function calls does return a promise, but you're throwing them away instead of awaiting them. Just use map instead, and you can await the array of promises that you'll get with Promise.all:
  19.  
  20. ```javascript
  21. async function printFiles () {
  22. const files = await getFilePaths();
  23.  
  24. await Promise.all(files.map(async (file) => {
  25. const contents = await fs.readFile(file, 'utf8')
  26. console.log(contents)
  27. }));
  28. }
  29. ```
Add Comment
Please, Sign In to add comment