Search code examples
javascripttwitterthunkkoa

Koa and Twitter - "Thunking" does not work


I've gotten some third party asynchronous functions to work with Koa through thunking, either by wrapping the function like so: var thunkedFunction = function(params) { return function(callback) { originalFunction(params, callback) }; ) or using the node thunkify library.

However when I try this with ntwitter's stream like so:

var streamThunk = thunkify(tw.stream);
var stream = yield streamThunk("statuses/filter", {track: track});

I get the following error: "Cannot read property stream_base of undefined".

Digging deeper into ntwitter (built on node-twitter) I see that the Twitter.prototype.stream function calls this.options.stream_base, and this.options is defined when I call it normally i.e. tw.stream(function(stream) {...}); but undefined when I thunk the function. Is there any reason that the function loses its scope when thunked, and is there a way to circumvent this?


Solution

  • Notice that thunkify doesn't see the tw object. So, the way it's designed, it has no way of knowing the context (tw in your case) of the function it's getting (tw.stream).

    The function returned by thunkify will pass along whatever this context it's called with (source: node-thunkify/index.js).

    This means you should be able to change the second line in your example to:

    var stream = yield streamThunk.call(tw, "statuses/filter", {track: track});
    

    Read more about call.