Skip to content

Instantly share code, notes, and snippets.

@hitsthings
Created December 3, 2019 07:20
Show Gist options
  • Save hitsthings/44625c239dd8efac0d43c2e0cb176fae to your computer and use it in GitHub Desktop.
Save hitsthings/44625c239dd8efac0d43c2e0cb176fae to your computer and use it in GitHub Desktop.
Async iterators, generators, and try-finally

Turns out JS can throw an error on a line like return 42;

generator - loops forever sleeping 1s at a time, and when you try to stop it, it waits 1s and then throws an error.

iteration - calls generator via a for-await and attempts to return within the iteration. This forces iteration to wait for generators finally section to run which includes a 1s await!

async function * generator() {
try {
let i = 0;
while(true) {
await sleep(1000);
yield i++;
}
} catch(e) {
console.log('caught', e);
} finally {
console.log('finally');
await sleep(1000);
throw new Error('finally-await');
}
}
async function iteration() {
try {
for await (const g of generator()) {
return 42;
}
} catch (e) {
console.log('caught', e);
return 43;
}
}
function main() {
iteration().then(
a => console.log('res', a),
b => console.log('rej', b)
);
}
const sleep = n => new Promise(res => setTimeout(res, n));
main();
/*
Output:
finally
caught Error: finally-await
at generator (<anonymous>:13:15)
at async iteration (<anonymous>:20:7)
res 43
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment