terminate if the source yields too slow
yarn add @async-generators/timeout
This package's main entry points to a commonjs distribution.
Additionally, the module entry points to a es2015 distribution, which can be used by build systems, such as webpack, to directly use es2015 modules.
timeout() returns an iterable that, when iterated, wraps and iterates the source iterable. If the time taken to return next() is greater than ms then an error is thrown to signify timeout.
example.js
const timeout = require("@async-generators/timeout").default;
async function* source() {
yield 1;
await new Promise(r => setTimeout(r, 500));
yield 2;
}
async function main() {
for await (let item of timeout(source(), 250)) {
console.log(item);
}
}
main().catch(console.log);Execute with the latest node.js:
node --harmony-async-iteration example.js
output:
1
Error: timed out
This library is fully typed and can be imported using:
import timeout from '@async-generators/timeout');It is also possible to directly execute your properly configured typescript with ts-node:
ts-node --harmony_async_iteration example.ts