0

I have the following scenario to implement in node.

  1. Printing random words inside a loop.
  2. There is an asynchronous function to call for that (printRandomWord).
  3. The function has a delay of 0.5 seconds to get the response.
  4. I have to call this function inside a loop from 1 to 20.
  5. It takes 10 seconds to print 20 random words since the printRandomWord has a 0.5 s delay.

What I want to do is, print 20 random words in less than 1 second.

I was told that there is a way to do that, but I couldn't find the solution yet.

This is my code.

 const printWords = async () => {
   for (let x = 1; x <= 100; x++) {
     console.log(await printRandomWord());
   }
 };
georgeawg
  • 46,994
  • 13
  • 63
  • 85
Shashika
  • 4,216
  • 7
  • 42
  • 69
  • 2
    You can use an array of Promises and call `Promise.all` on them, or if you really aren't doing anything else in the function and the order of logs doesn't matter, you can just do `printRandomWord().then(console.log).catch(handleError)` inside the loop – CertainPerformance Dec 17 '19 at 05:38
  • Or something along the lines of `Promise.all(Array.from({length: 100}, printRandomWord)).then(console.log);`. This prints all words at once. – Thomas Dec 17 '19 at 06:53

0 Answers0