Emil
Emil

Reputation: 681

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?

Upvotes: 9

Views: 1704

Answers (2)

Bergi
Bergi

Reputation: 664538

There simply are no asynchronous generator functions in Node.js.

Yet. They're still figuring out what their semantics would be, see the async iteration proposal.

Upvotes: 1

Meirion Hughes
Meirion Hughes

Reputation: 26408

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.

Upvotes: 8

Related Questions