Trying to understand JS async/await

62 Views Asked by At

I'm learning async/await and created a small fiddle @ https://jsfiddle.net/mpycio/rb8taLt7/.

const parse = async (num) => {
    let res = await new Promise(resolve => 
    setTimeout(() => {resolve(num * 2)}, 0)
  )
  
  return res
}

[1,2,3,4].forEach(async (num) => {
    log(`parsing:  ${num}`);
  const res = await parse(num);
  log(`parsing result: ${res}`);
})

I'm missing something as I was especting the logged results to be:

parsing: 1

parsing result: 2

parsing: 2

parsing result: 4 ...

So my question is how to correctly write the forEach loop to guarantee that result of a promise is resolved inside the loop?

Edit1: So this has already been answered before, solution is indeed for of loop: https://jsfiddle.net/mpycio/rb8taLt7/4/

0

There are 0 best solutions below