2

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/

Community
  • 1
  • 1
Mahakala
  • 761
  • 1
  • 10
  • 16
  • what you want is to parse it synchronously, you don't need a async await function for this – marvel308 Sep 15 '17 at 09:48
  • @marvel308: I actually do need async/await, this is just an example but I have a parse function that will make a call to a database and I will need to wrap it in a promise. – Mahakala Sep 15 '17 at 09:51

0 Answers0