Skip to content

Instantly share code, notes, and snippets.

@timoxley
Last active September 24, 2020 17:09
Show Gist options
  • Save timoxley/22bca8e7e507cdb9dd42aaf7d67372e4 to your computer and use it in GitHub Desktop.
Save timoxley/22bca8e7e507cdb9dd42aaf7d67372e4 to your computer and use it in GitHub Desktop.
const Emitter = require('events')
const emitter = new Emitter()
// Currently, (Node v14.12.0) this just prints 'iterating', waits a moment, then silently exits 0.
// But adding at least one event triggers the full flow of: iterating, caught, finally, rejected
// thinking maybe throw() should call errorHandler?
;(async () => {
const it = Emitter.on(emitter, 'test')
setTimeout(() => {
// emitter.emit('test') // uncomment to trigger full error flow
it.throw(new Error('expected'))
}, 100)
try {
console.log('iterating')
for await (const t of it) {
console.log({ t })
}
console.log('iterated')
} catch (err) {
console.log('caught err', err)
throw err
} finally {
console.log('finally')
}
console.log('ending...')
})().then(() => {
console.log('done')
}, (err) => {
console.log('rejected with', err)
})
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
async function* T() {
await wait(500)
yield 1
await wait(500)
yield 2
}
// this logs: iterating, { t: 1 }, iterated, finally, ending..., done
// but now with a bonus UnhandledPromiseRejectionWarning (need to attach .catch to it.throw to handle :/)
// note: according to spec this *should* wait for first yield, that's fine.
;(async () => {
const it = T()
setTimeout(() => {
it.throw(new Error('expected'))
}, 100) // happens before first yield
try {
console.log('iterating')
for await (const t of it) {
console.log({ t })
}
console.log('iterated')
} catch (err) {
console.log('caught err', err)
throw err
} finally {
console.log('finally')
}
console.log('ending...')
})().then(() => {
console.log('done')
}, (err) => {
console.log('rejected with', err)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment