0

I want to create a function "processArray(array)" that when called it will console.log item after item in the array with a delay of 1 sec between each log.
So I've managed to do so with this code (A):

function delay() {
      return new Promise(resolve => setTimeout(resolve, 1000));
    }
    
    async function delayedLog(item) {
      await delay();
      console.log(item);
    }
    
    async function processArray(array) {
      for (let i = 0; i < array.length ; i++){ 
        await delayedLog(array[i]);
      }
    }
    
    processArray([1, 2, 3]);

But this code (B) doesn't work:

function delay() {
      return new Promise(resolve => setTimeout(resolve, 1000));
    }
    
    async function delayedLog(item) {
      await delay();
      console.log(item);
    }
    
    function processArray(array) {
      for (let i = 0; i < array.length ; i++){ 
        (async () => {
        await delayedLog(array[i]);
     })();
      }
    }
    
    processArray([1, 2, 3]);

Why would B code not work? the only different is I've used an anonymous async function inside the for loop instead of declaring the processArray function async.

Haddar Macdasi
  • 3,477
  • 8
  • 37
  • 59

0 Answers0