Symbol asyncIterator Enables for await

Make any object consumable with for await by implementing Symbol.asyncIterator: next() returns a promise per step and callers can break out early.

JavascriptData Fetching

Code

javascriptsnippet
30 lines
// Symbol.asyncIterator: 让对象原生支持 for await...of 消费
class Poller {
  constructor(tasks) {
    this.tasks = tasks;
    this.index = 0;
  }

  // 协议约定:返回带 next() 的对象,next 返回 Promise<{ value, done }>
  [Symbol.asyncIterator]() {
    return {
      next: async () => {
        if (this.index >= this.tasks.length) {
          return { done: true, value: undefined };
        }
        const value = this.tasks[this.index++];
        return { done: false, value };
      },
    };
  }
}

const jobs = new Poller(['scan-a', 'scan-b', 'scan-c']);

// for await 逐个消费;提前 break 停止拉取
for await (const job of jobs) {
  console.log('job  :', job);
  if (job === 'scan-b') break;
}

console.log('stop : remaining', jobs.tasks.length - jobs.index, 'tasks never pulled');

Output

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

job  : scan-a
job  : scan-b
stop : remaining 1 tasks never pulled

How it works

Symbol asyncIterator Enables for await reduces to the class Poller.

Iteration happens inside for await (const job of jobs) — everything outside it runs once. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

The file’s state is a handful of top-level bindings: jobs.

The result comes back as an object carrying true.

What to watch for

  • The guard this.index >= this.tasks.length short-circuits the flow with an early return when its condition holds.

Using it

The demo output is labeled (stop : remaining), so every printed line maps back to its originating operation.

The call returns true.

Key statements

return { done: true, value: undefined };
for await (const job of jobs) {
  console.log('job  :', job);
  if (job === 'scan-b') break;
}
return { done: false, value };

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `jobs`.
What does the code return?
An object carrying `true`.