InterviewHubPRO
Section Overview
Q510

Question 510 of 521

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

98%
JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

What is the difference between synchronous and asynchronous generators?

Synchronous and asynchronous generators differ in how they produce values and handle asynchronous operations.

Synchronous generator:

javascript
 function* syncGenerator() {
   yield 1;
   yield 2;
   yield 3;
 }

 const gen = syncGenerator();
 console.log(gen.next()); // { value: 1, done: false }
 console.log(gen.next()); // { value: 2, done: false }

Asynchronous generator:

javascript
 async function* asyncGenerator() {
   yield await Promise.resolve(1);
   yield await Promise.resolve(2);
   yield await Promise.resolve(3);
 }

 (async () => {
   for await (const value of asyncGenerator()) {
     console.log(value); // 1, 2, 3
   }
 })();

Comparison:

Synchronous GeneratorAsynchronous Generator
function*async function*
Returns iteratorReturns async iterator
.next() returns { value, done }.next() returns Promise<{ value, done }>
Used with for...ofUsed with for await...of
Cannot await insideCan await inside

Practical example - data streaming:

javascript
 // Sync generator - in-memory data
 function* readFileSync(lines) {
   for (const line of lines) {
     yield line;
   }
 }

 // Async generator - streaming data
 async function* readFileAsync(filePath) {
   const stream = createReadStream(filePath);
   const reader = stream.getReader();

   while (true) {
     const { done, value } = await reader.read();
     if (done) break;
     yield value;
   }
 }

Async generator with delays:

javascript
 async function* ticker(interval, max) {
   let count = 0;
   while (count < max) {
     await new Promise(resolve => setTimeout(resolve, interval));
     yield count++;
   }
 }

 (async () => {
   for await (const tick of ticker(1000, 5)) {
     console.log(tick); // 0, 1, 2, 3, 4 (one per second)
   }
 })();

Combining generators:

javascript
 async function* fetchPages(urls) {
   for (const url of urls) {
     const response = await fetch(url);
     yield await response.json();
   }
 }

 async function* processPages(urls) {
   for await (const page of fetchPages(urls)) {
     yield processPage(page);
   }
 }