for await... of vs using await inside the body of the for..of iteration

Viewed 552

Consider the following code:

const array_of_promises = len => Array.from({length:len},
    () => Promise.resolve(`Resolved with: ${Math.random()*100|0}`));

(async() => {
    for await (const x of array_of_promises(5)) { // await here
        console.log(x);
    }
})();
What benefits do I get here over simply using the following iteration? this seems to produce the same result.

(async() => {
    for (const x of array_of_promises(5)) {
        console.log(await x); // await here
    }
})();

The result is the same in both cases. Let's say I want to consume a generator iterable asynchronously, would using await in the body of the for loop not suffice? according to the spec, [Symbol.asyncIterator]() returns an iterator that produces Promise wrapped {value:x, done:boolean} values by consuming it, can I not just await it inside the for iteration?

0 Answers
Related