Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demystifying Async Programming in Javascript - Generator internals reverting adder
function* adder(initialValue) {
let sum = initialValue;
let lastSum = initialValue;
let temp;
while (true) {
try {
temp = sum;
sum += yield sum;
lastSum = temp;
} catch (e) {
sum = lastSum;
}
}
}
const add = adder(0);
console.log(add.next()); // 0
console.log(add.next(1)); // 1
console.log(add.next(2)); // 3
console.log(add.throw(new Error('BOO)!'))); // 1
console.log(add.next(4)); // 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.