0

In this code, I am getting a value 34 in the newArr. Which is expected and correct.

var arr = [1, 2, 34, 5, 6, 67, 4]
var val = 34

var newArr = []

arr.forEach((elm) => {

  if (val == elm)
    newArr.push(elm)
})

console.log(newArr)

But when I am using async await I am not getting any value in newArr.

var arr = [1, 2, 34, 5, 6, 67, 4]
var val = 34

var newArr = []

arr.forEach(async(elm) => {
  await setTimeout(function() {}, 10);
  if (val == elm)
    newArr.push(elm)
})

console.log(newArr)

I am new to Javascript and not able to understand why this is not working as I am expecting.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • setTimeout does not return a promise – mplungjan Nov 16 '21 at 13:04
  • @mplungjan That's right but unrelated and therefore probably more confusing than helpful. `await new Promise(r => setTimeout(r, 10));` doesn't change the output and the visible behavior. – jabaa Nov 16 '21 at 13:08
  • I assume this is an X/Y problem but we will not know if OP does not give better usecase. – mplungjan Nov 16 '21 at 13:11
  • I was going to answer you, but the question was flagged as duplicated. this is normal behavior since the logic of javascript is to execute line by line. and since you have async execution, this will lead us to print the newArr before finishing the async code. you can wrapp the arr.forEach with Promise.resolve and print it using await or then promise – Mohammed naji Nov 16 '21 at 13:12
  • var arr = [1, 2, 34, 5, 6, 67, 4] var val = 34 var newArr = [] arr.map(async(elm) => { if (val == elm) await newArr.push(elm) }) console.log(newArr) – Aks Nov 17 '21 at 07:38
  • I don't see any use of setTime out function – Aks Nov 17 '21 at 07:39

0 Answers0