How were generators historically used to write asynchronous code before async/await existed?
Short answer
Generators combined with a driver function (like early versions of co or redux-saga) let you yield Promises and have the driver automatically call .next() again once each Promise resolved, producing async-looking code with synchronous-looking syntax — the direct conceptual…
Advertisement
AModel answer
Generators combined with a driver function (like early versions of co or redux-saga) let you yield Promises and have the driver automatically call .next() again once each Promise resolved, producing async-looking code with synchronous-looking syntax — the direct conceptual predecessor to async/await.
function run(genFn) {
const gen = genFn();
function step(input) {
const { value, done } = gen.next(input);
if (!done) value.then(step);
}
step();
}
run(function* () {
const data = yield fetch('/api').then(r => r.json());
console.log(data);
});Real-world example
Understanding why redux-saga still uses generators today, and how async/await effectively standardized this pattern.
Likely follow-ups
- Why did the language eventually add async/await instead of relying purely on generator-driver libraries?
Related topics