Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare async generator function

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:

enter image description here

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?

like image 815
Emil Avatar asked Jul 03 '17 10:07

Emil


1 Answers

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.

like image 195
Meirion Hughes Avatar answered Oct 01 '22 12:10

Meirion Hughes