JavaScript generator: sync vs async


This article goes over the difference between synchronous and asynchronous generators.

Sync

Example of a sync generator:

const fruits = ['Apple', 'Banana', 'Orange'];

function* getFruitsIterator() {
  for (const fruit of fruits) {
    yield fruit;
  }
}

const getFruits = getFruitsIterator();

console.log(getFruits.next());
console.log(getFruits.next());
console.log(getFruits.next());
console.log(getFruits.next());

Which outputs the logs:

{ value: 'Apple', done: false }
{ value: 'Banana', done: false }
{ value: 'Orange', done: false }
{ value: undefined, done: true }

Async

Example of an async generator:

const names = [Promise.resolve('Adam'), Promise.resolve('Eve')];

async function* getNamesIterator() {
  try {
    for (const name of names) {
      yield name;
    }
  } catch (error) {
    throw error;
  }
}

(async () => {
  const getNames = getNamesIterator();

  console.log(await getNames.next());
  console.log(await getNames.next());
  console.log(await getNames.next());
})();

Which outputs the logs:

{ value: 'Adam', done: false }
{ value: 'Eve', done: false }
{ value: undefined, done: true }

Demo

Repl.it:



Please support this site and join our Discord!