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.
Before async and await existed, libraries ran generators that yielded promises. It is a good way to see what await does.
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);3Each 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.