MK.
MK.

Reputation: 34557

Trying to thunkify a callback based function to use with generators (yield), doesn't work

I am trying to synchronously invoke a regular call-back style function in koa using generators. The following approach works:

  var res = yield function (cb) {
    myDaoObject.load(function (err, res) {
       cb(err, res);
    })
  };

So I wont to replace it with the proper library use which should be equivalent:

var ld = thunkify(myDaoObject.load);
var res = yield ld();

And that doesn't work. Aren't these supposed to be the same thing?

Upvotes: 1

Views: 167

Answers (1)

Bergi
Bergi

Reputation: 664650

Actually you hardly need to use thunkify here, as your function doesn't take an argument. You can (and should) however simplify it to

yield function(cb) { myDaoObject.load(cb); }

and possibly even further to just

yield myDaoObject.load;

which would work if load was not a method that used this. You will have to bind it to the object you want it get called upon:

yield myDaoObject.load.bind(myDaoObject);

The same problem was with your thunkify call - which was otherwise fine (albeit unnecessary).

Upvotes: 2

Related Questions