Array fromAsync Collects Async Iterables

Collect async iterables into arrays with Array.fromAsync, which awaits every yielded value, accepts a per-item mapper, and works on sync iterables too.

JavascriptData Fetching

Code

javascriptsnippet
19 lines
// Array.fromAsync(ES2024):等待每个 yield 的值再收集成数组
async function* fetchPages() {
  // 模拟分页拉取:每次 yield 一页
  yield ['user-1', 'user-2'];
  yield ['user-3'];
  yield ['user-4', 'user-5'];
}

// 不传 mapper:得到「页的数组」,嵌套结构原样保留
const pages = await Array.fromAsync(fetchPages());
console.log('pages  :', JSON.stringify(pages));

// 传 mapper:每个 yield 的元素先映射再收集,这里取每页长度
const counts = await Array.fromAsync(fetchPages(), (page) => page.length);
console.log('counts :', counts.join(','));

// 同步可迭代对象同样适用:Set 去重后的成员逐个 await 收集
const unique = await Array.fromAsync(new Set(['a', 'b', 'a']));
console.log('set    :', unique.join(','));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

pages  : [["user-1","user-2"],["user-3"],["user-4","user-5"]]
counts : 2,1,2
set    : a,b

How it works

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Everything operates on top-level bindings: pages, counts, unique.

Using it

Running the file prints labeled results such as pages :, counts :, set : — each operation’s effect is visible in the output.

Key statements

const counts = await Array.fromAsync(fetchPages(), (page) => page.length);
const unique = await Array.fromAsync(new Set(['a', 'b', 'a']));
const pages = await Array.fromAsync(fetchPages());

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Its state lives in module-level bindings: `pages`, `counts`, `unique`.