break-async-iterator
Problem:
const neverResolves = process.stdin
async function* stuck() {
for await (const i of neverResolves) {
yield
}
}
let i = stuck()
i.next()
i.return()
Solution
const breakAI = require('break-async-iterator')
const notStuck = breakAI(breakable => async function*() {
try {
for await (const i of breakable(neverResolves)) {
yield
}
} finally {
}
})
let i = notStuck()
i.next()
i.return()
Install
npm i break-async-iterator
Usage
API
breakAI(breakable => async function* asyncGenerator(){...})
-
breakable
A function that takes an iterator or a promise and returns a breakable version of the same
-
Returns An async generator that returns an iterator (wrapped around the one returned by asyncGenerator()
) that's able to interrupt any iterators or promises (that were passed through breakable()
) when its .return()
or .throw()
are called
Example
If you have an async generator function like this:
async function* asyncGenerator() {
for await (const value of anotherAsyncIterator) {
yield value
}
yield await aPromise
}
Then simply wrap it like this
const asyncGenerator = breakAI(breakable => async function*() {
for await (const value of breakable(anotherAsyncIterator)) {
yield value
}
yield await breakable(aPromise)
})