Created
          December 1, 2018 11:49 
        
      - 
      
- 
        Save ObsidianCat/8f260677ae344cf7023c3f7fecf33242 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
    
  
  
    
  | const { getRandomWordSync, getRandomWord } = require("word-maker"); | |
| const fs = require("fs"); | |
| console.log("It works!"); | |
| // YOUR CODE HERE | |
| //Additional functions | |
| //asynchronous in loop | |
| async function asyncInLoopWithPromiseAllInOrder(){ | |
| const promises = []; | |
| const results = [] | |
| for (let i = 1; i <= 100; i++) { | |
| //Work around, to avoid fast fail of Promise.all() | |
| //Push promises with attached catch | |
| promises.push( | |
| getRandomWord({ withErrors: true }) | |
| .then(value => { | |
| results[i-1] = `${i}: ${value}`; | |
| }) | |
| .catch(() => { | |
| results[i-1] = `${i}: Doh!`; | |
| }) | |
| ); | |
| } | |
| await Promise.all(promises); | |
| results.forEach(item => console.log(item)) | |
| } | |
| async function asyncInLoopWithAwait() { | |
| for (let i = 1; i <= 100; i++) { | |
| try { | |
| //Wait for getting response in every iteration | |
| let word = await getRandomWord({ withErrors: true }); | |
| console.log(`${i}: ${word}`); | |
| } catch (error) { | |
| console.log(`${i}: Doh!`); | |
| } | |
| } | |
| } | |
| //asyncInLoopWithAwait() | |
| asyncInLoopWithPromiseAllInOrder() | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Good stuff. I hope you don't mind me suggesting a few more refinements...
Maintaining both
resultsandpromisesarrays is a bit ugly and error prone for future maintainers. You can just do this:It would be nice to use
async/awaitcompletely, but anawaitwill obviously block the loop. To circumvent this, we can use an async IIFE:This does look a bit uglier though and ultimately (and usually in modern js), modifying a value from within a
forloop is usually a code smell that it would be better in a more functional way. Here the code creates an empty array and maps it with the async function. Finally, it's also a bit nicer to join the printed results with a new line rather than iterating them again.