Skip to content

Instantly share code, notes, and snippets.

@bradennapier
Last active November 28, 2018 02:22
Show Gist options
  • Save bradennapier/6d6ed5cd6f2c2df0b0359580ce585d36 to your computer and use it in GitHub Desktop.
Save bradennapier/6d6ed5cd6f2c2df0b0359580ce585d36 to your computer and use it in GitHub Desktop.
const ms = delay => new Promise(resolve => setTimeout(resolve, delay));
async function* iterate() {
let i = 0;
try {
const done = false;
while (!done) {
try {
await ms(1000);
i += 1;
console.log('iterates: ', i);
yield i;
} catch (e) {
switch (e) {
case '>5': {
console.log(`Injected at ${i}: >5`);
break;
}
default: {
console.log(`Catches at ${i}:`, e);
break;
}
}
yield;
}
}
} finally {
console.log('.return() called!');
}
}
async function run() {
const iter = iterate();
let i;
for await (i of iter) {
console.log('forawait: ', i);
if (i >= 5) {
if (i >= 10) {
iter.return('done');
} else {
iter.throw('>5');
}
}
}
console.log('run finishes with: ', i);
}
run();
@bradennapier
Copy link
Author

bradennapier commented Nov 28, 2018

When run, the output is as follows:

iterates:  1
forawait:  1
iterates:  2
forawait:  2
iterates:  3
forawait:  3
iterates:  4
forawait:  4
iterates:  5
forawait:  5
Injected at 5: >5
iterates:  6
forawait:  6
Injected at 6: >5
iterates:  7
forawait:  7
Injected at 7: >5
iterates:  8
forawait:  8
Injected at 8: >5
iterates:  9
forawait:  9
Injected at 9: >5
iterates:  10
forawait:  10
.return() called!
run finishes with:  10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment