JS Built-ins
← Array18 / 226
ArrayArray.fromAsyncadvanced

Array.fromAsync() β€” collect from a generator

πŸ“– Usage Example
async function* gen() { yield 1; yield 2; yield 3 }
const arr = await Array.fromAsync(gen())
// β†’ [1, 2, 3]

Use Array.fromAsync() to collect all yielded values from an async generator into an array.

Array.fromAsync() β€” async generators

Array.fromAsync() can consume an async generator β€” a function* or async function* β€” and collect every yielded value into a plain array.

This exercise simulates that behaviour synchronously: collect values from a regular generator using Array.from().

Challenge: Implement collectFromGenerator that runs a generator yielding 1, 2, 3 and returns [1, 2, 3].

collectFromGenerator() // β†’ [1, 2, 3]
πŸ’‘ Hints (2)
  • β€’ Generators are iterable β€” both `Array.from()` and `Array.fromAsync()` accept them.
  • β€’ `Array.fromAsync` would be used if the generator were `async function*` and yielded promises.