Skip to content

Instantly share code, notes, and snippets.

@kriskowal
Last active May 20, 2022 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kriskowal/c246e0cdc1f0d9fba3ec3c9c54bd7f9a to your computer and use it in GitHub Desktop.
Save kriskowal/c246e0cdc1f0d9fba3ec3c9c54bd7f9a to your computer and use it in GitHub Desktop.
const go = {
[Symbol.iterator]() {
const funcs = [];
const defer = func => funcs.push(func);
let index = 0;
const flush = () => {
let func;
while (func = funcs.pop()) {
func();
}
};
return {
next() {
if (index++ === 0) {
return {value: defer};
} else {
flush();
return {done: true};
}
},
return: flush,
};
}
};
for (const defer of go) {
console.log(0);
defer(() => console.log(4));
console.log(1);
defer(() => console.log(3));
console.log(2);
}
for (const defer of go) {
console.log(5);
defer(() => console.log(9));
console.log(6);
defer(() => console.log(8));
console.log(7);
throw new Error('10');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment