0

I'm going back and forth on StackOverflow trying to find this specific answer, but I can't find anything that works. "Test" should be defined after the execution of the async function inside the loop. If I try to console log "Test" it returns undefined. How can I wait for the loop execution to proceed in the stack?

let array = [1, 2, 3, 4, 5]
let test;   

array.forEach(async el => {  
  await setTimeout(() => {
    if(el === 5) {
      test = true      
    }
  }, 5000)
})

console.log(test)

I also tried defining an async function with the loop into it and then calling an IIFE, awaiting for the function and console logging the variable. It returns the same undefined.

let array = [1, 2, 3, 4, 5]
let test;   

async function hey() {
    array.forEach(async el => {  
  await setTimeout(() => {
    if(el === 5) {
      test = true      
    }
  }, 5000)
})
}

(async () => {
  await hey();
  console.log(test);  
})()
igortp
  • 179
  • 1
  • 14
  • My answer is not the correct one. Seems like it's not working as it should. Please 'unaccept' it so i can delete it :D thanks – Mihai T Nov 16 '20 at 09:24

1 Answers1

0

You need to return a promise from your async function. Otherwise you cannot ' await '. Not really sure what you are trying to do inside that foreach loop.

let array = [1, 2, 3, 4, 5]
let test;

async function hey() {
  return new Promise(resolve => {
    array.forEach( el => {


      setTimeout(function() {
        el === 5 ? resolve(true) : resolve(false)

      }, 5000);

    })
  })
}

(async () => {
  test = await hey();
  console.log(test);
})()
Mihai T
  • 17,254
  • 2
  • 23
  • 32
  • I added the false by mistake. But it's working once I promisify the forEach loop. Thx – igortp Nov 16 '20 at 09:06
  • Hmm i have second thoughts about my answer. I will check it some more. Please make sure it's working correctly in your application – Mihai T Nov 16 '20 at 09:09