I am trying to create async generator function in Node.js, but it seems to be impossible.
Version of my Node.js: 7.6.0.
My code:
async function* async_generator(){
for(let i = 0; i < 10; i++){
yield await call_to_async_func(i);
};
}
Error I got:
Does anyone knows what is the problem? Why I can't create async generator function while I can create generator function or async function Independently?
It is there and it does work, but currently it is behind a harmony flag.
example.js
async function* async_generator() {
for (let i = 0; i < 10; i++) {
yield await new Promise(r => setTimeout(_ => r("hello world"), 100))
};
}
async function main(){
for await (let item of async_generator()){
console.log(item);
}
}
main().catch(console.log);
run with (works for me in node v8.5.0)
node --harmony-async-iteration example.js
be aware that the proposal is still at stage-3 and if you want to use it in the browser you'll likely also need to transpile with typescript or babel.
update:
as of node 9, async generators are staged. You can enable it simply with --harmony
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With