Does node.js support yield?

后端 未结 10 675
误落风尘
误落风尘 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:48

    Update 2014: Node does support callbacks now. The following is a post from 2010.


    You should use callbacks. If the function does something asynchronously, you may also want a continuation callback (continuation is a bad word, since it also means something else, but you get my point.)

    primes(function(p) {
      if (p > 100) return false // i assume this stops the yielding
      do_something(p)
      return true // it's also better to be consistent
    }, function(err) { // fire when the yield callback returns false
      if (err) throw err // error from whatever asynch thing you did
      // continue...
    })
    

    Updated with example code

    I flipped it, so that it returns true on complete (since null, false and undefined all evaluate to false anyways).

    function primes(callback) {
      var n = 1, a = true;
      search: while (a)  {
        n += 1;
        for (var i = 2; i <= Math.sqrt(n); i += 1)
          if (n % i == 0)
            continue search;
        if (callback(n)) return
      }
    }
    
    primes(function(p) {
      console.log(p)
      if (p > 100) return true
    })
    

提交回复
热议问题