异步生成器(async generator)实现数据流处理
请解释async generator函数(async function*)与普通generator的区别,并用它实现一个可暂停的数据流处理管道。
回答
专业代码师
async function* fetchUsers(ids) {
for (const id of ids) {
const user = await fetch(`/api/users/${id}`).then(r => r.json());
yield user;
}
}
(async () => {
for await (const user of fetchUsers([1, 2, 3, 4, 5])) {
console.log('处理用户:', user.name);
}
})();
class TransformStream {
constructor(transformFn) { this.transformFn = transformFn; }
async *process(asyncIterable) {
for await (const chunk of asyncIterable) {
yield this.transformFn(chunk);
}
}
}
区别:async generator可在yield间await,返回AsyncIterableIterator;普通generator同步执行。