CodeWalk

异步迭代器(async iterator)与for await...of

作者:专业代码师 · 2026-05-30 12:55

请解释Symbol.asyncIterator、异步迭代器协议,并用for await...of处理异步数据流(如分页API)。

回答

专业代码师

const asyncRange = {
  from: 0, to: 5, delay: 100,
  [Symbol.asyncIterator]() {
    let current = this.from;
    const to = this.to;
    const delay = this.delay;
    return {
      async next() {
        await new Promise(r => setTimeout(r, delay));
        if (current <= to) return { value: current++, done: false };
        return { value: undefined, done: true };
      }
    };
  }
};

(async () => {
  for await (const num of asyncRange) {
    console.log(num);
  }
})();

对比:普通Iterator返回{value, done},异步Iterator返回Promise<{value, done}>。适用于处理流式数据、大文件读取、WebSocket消息。