Does node.js support yield?

后端 未结 10 1029
误落风尘
误落风尘 2021-01-31 01:51

Is there any way to get generators into node.js?

I\'m currently faking them with callbacks, but I have to remember to check the response of the callback inside of my gen

10条回答
  •  感动是毒
    2021-01-31 02:32

    Yes Node.js and JavaScript now have both synchronous iterators (as of atleast Node v6) and asynchronous iterators (as of Node v10):

    An example generator/iterator with synchronous output:

    // semi-pythonic like range
    function* range(begin=0, end, step=1) {
      if(typeof end === "undefined") {
        end = begin;
        begin = 0;
      }
      for(let i = begin; i < end; i += step) {
        yield i;
      }
    }
    
    for(const number of range(1,30)) {
      console.log(number);
    }

    A similar async generator/iterator.

    const timeout = (ms=1000) => new Promise((resolve, reject) => setTimeout(resolve, ms));
    
    async function* countSeconds(begin=0, end, step=1) {
      if(typeof end === "undefined") {
        end = begin;
        begin = 0;
      }
      for(let i = begin; i < end; i += step) {
        yield i;
        await timeout(1000);
      }
    }
    
    (async () => {
      for await (const second of countSeconds(10)) {
        console.log(second);
      }
    })();

    There is a lot to explore here are some good links. I will probably update this answer with more information later:

    • Generators
    • Generator functions
    • Iterable Protocol
    • Iterator Protocol
    • Async Generators
      • Jake Archibald's Article on Async Generators
    • Async Iterators
    • for await ... of

提交回复
热议问题