3

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?

spider monkey
  • 304
  • 1
  • 4
  • 10
  • [You should not be using either code](https://stackoverflow.com/a/59695815/1048572) on arrays of promises. – Bergi May 17 '20 at 18:54
  • "*I want to consume a generator iterable asynchronously*" - it's unclear what kind of iterable you are talking about here. Is it the array of promises, or was that just a bad example? Is it a generator that yields promises? Is it an asynchronous generator (which is not a normal iterable, and is what `for await` was meant for)? – Bergi May 17 '20 at 18:58

0 Answers0