0

I'm trying to understand async-await but it doesn't matter how much I read about it it still performs different from what I expect.

Here is my code:

async function exampleFunction(myArray){
    for await (let item of myArray) {
        console.log('ITERATION')
        let dataInfo = await getDataInfo(item.data)
        console.log(dataInfo)
    }
}

async function getDataInfo(dataPoint){
    let info1 = await awaitableFunction1(dataPoint)
    let info2 = await awaitableFunction2(dataPoint)
    return [info1,info2]
}

If I pass exampleFunction() an array of 3 items (3 resolved values, NOT 3 promises), I would expect it to log:

ITERATION
ITERATION
ITERATION
[dataInfo1]
[dataInfo2]
[dataInfo3]

Instead it logs:

ITERATION
[dataInfo1]
ITERATION
[dataInfo2]
ITERATION
[dataInfo3]

Proving that the code is not asynchronous. What is wrong with it? Thanks

Hiperfly
  • 227
  • 1
  • 10
  • 3
    [Never use `for await … of` on an array](https://stackoverflow.com/q/59694309/1048572)! – Bergi Aug 05 '21 at 08:52
  • 3
    Asynchronous =/= parallel execution. You await every iteration of your loop, so the output you show is to be expected. If you want to start all async operations/promises at the same time, with no regard to the order in which they are executed, use `Promise.all(myArray.map(m => getDataInfo(m.data))` – nbokmans Aug 05 '21 at 08:53
  • 1
    Your expected outcome would require that the code inside your loop somehow simultaneously stops *and* continues at the same time, which would make execution extremely unpredictable. – deceze Aug 05 '21 at 08:59
  • 1
    Your code *is* asynchronous. The loop is *sequential* though, since you `await` in each iteration. – Bergi Aug 05 '21 at 09:00
  • Damn, my understanding of `await` was that when it encounters an await in one of the iterations of the loop (iteration `A`), it would continue execution with the next iteration `B` until `A` was resolved, and then it would come back and continue executing iteration `A` – Hiperfly Aug 05 '21 at 09:08
  • 1
    That would require your code to bifurcate and somehow run two and more instances of your function/loop in parallel, which opens all sorts of cans of worms. `await` means *don't do anything until this async operation is resolved.* – deceze Aug 05 '21 at 09:09

0 Answers0