← 中文资源

简体中文版本

Array.fromAsync 收集异步可迭代

Array.fromAsync 等待每个 yield 的值再收集:分页异步流一次性摊平成数组,可选 mapper 对每页做映射,Set 等同步可迭代对象同样适用。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

每个异步步骤都被 await,拒绝会在发起调用的那一行浮出。 pages、counts、unique 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 直接运行文件,输出会带上标签,比如 counts :——输出的每一行都能指回产生它的那次调用。

常见问题

除了语言工具链还要下载什么吗?

除了这个语言的工具链,什么都不用再下载。 文件的状态由几个模块级绑定持有:pages、counts、unique。

核心语句

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());

代码示例

// 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(','));