Skip to content
jshacks.dev
Functions

Use a generator to implement an async coroutine

Use a generator to implement an async coroutine in JavaScript: a small runner awaits each yielded promise, which is how async await works. Node.js 24.

1 min read
Summarize in AI

Before async and await existed, libraries ran generators that yielded promises. It is a good way to see what await does.

JavaScript
const run = (genFn) =>
  new Promise((resolve, reject) => {
    const gen = genFn();
    const step = (method, arg) => {
      let result;
      try {
        result = gen[method](arg);
      } catch (err) {
        return reject(err);
      }
      if (result.done) return resolve(result.value);
      Promise.resolve(result.value).then(
        (v) => step('next', v),
        (e) => step('throw', e),
      );
    };
    step('next');
  });

const delay = (ms, v) => new Promise((r) => setTimeout(r, ms, v));

const total = await run(function* () {
  const a = yield delay(5, 1);
  const b = yield delay(5, 2);
  return a + b;
});
console.log(total);
Text
3

Each yield hands a promise to the runner, which waits for it and resumes the generator with the result, or throws the error into it. await does the same, built into the language.

Use async and await in real code. It has better stack traces and no runner to maintain. This is for understanding, and for the odd library that needs custom scheduling.

Also inAsync
Taggednode 24
Share

More snippets

Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read
Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.