Last active
November 28, 2018 02:22
-
-
Save bradennapier/6d6ed5cd6f2c2df0b0359580ce585d36 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When run, the output is as follows: