How to simulate JavaScript yield?

前端 未结 5 1804
误落风尘
误落风尘 2020-12-28 19:03

One of the new mechanisms available in JavaScript 1.7 is yield, useful for generators and iterators.

This is currently supported in Mozilla browsers only (that I\'m

5条回答
  •  囚心锁ツ
    2020-12-28 19:46

    I have started a little project that tries to do this with some callback trickery. Since it's impossible to create real coroutines in "standard" JavaScript, this doesn't come without a few caveats, e.g:

    • it's impossible to make this follow the iterator protocol (stuff like .next() etc.),
    • it's impossible to iterate through several generators at once,
    • you have to watch out not to let the wrong objects leave the generator's scope (e.g. by calling yield in a timeout – since this is "plain" JavaScript, there's no syntax restriction that prevents you from doing this),
    • exceptions in the generator are a little tricky,
    • and last not least, it's very experimental (just started this a few days ago).

    On the bright side, you have yield! :)

    The Fibonacci example from the MDC page would look like this:

    var fibonacci = Generator(function () {
      var fn1 = 1;
      var fn2 = 1;
      while (1){
        var current = fn2;
        fn2 = fn1;
        fn1 = fn1 + current;
        this.yield(current);
      }
    });
    
    console.log(fibonacci.take(10).toArray());
    

    Output:

    [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
    

    The project is on BitBucket at https://bitbucket.org/balpha/lyfe.

提交回复
热议问题