简体   繁体   中英

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM