john doe
john doe

Reputation: 111

Cannot yield next inside anonymous function

I have a generator function, like this:

function *(next) {
  this.redis.get('foo', function(e, r){
    console.log(r)
    yield next;
  })
}

I was thinking I could use a co style coding, by using var r = yield this.redis.get('foo') but apparently it does not work. The error here is that "next" does not exist anymore inside the anonymous function. How can I access it?

Upvotes: 0

Views: 1679

Answers (1)

alexpods
alexpods

Reputation: 48505

You can use yield keyword only in generators. To handle your problem you should make this.redis.get return a promise instead of accepting a callback. To do this, write a promisify function which converts a function expecting a callback into one that returns a promise:

function promisify(method) {
    return function() {
        var args = [].slice.call(arguments);
        return new Promise(function(resolve, reject) {
            method.apply(null, args.concat(function(e, r) {
                e ? reject(e) : resolve(r);
            }));
        });
    };
}

Then you can use it like this:

function *(next) {
    var r = yield promisify(this.redis.get)('foo');
    yield next;
}

Alternatively, some Promise libraries provide a promisify function. For example bluebird's Promise.promisify can be used like this:

var Promise = require( 'bluebird' );
function *(next){
    var redisGet = Promise.promisify( this.redis.get );
    yield redisGet( 'foo' );
    yield next;
}

Upvotes: 1

Related Questions