lorenzo-s
lorenzo-s

Reputation: 17010

Google's oauth2client.getToken() incorrectly returns when called with Q.ninvoke()

I'm using Google's node.js library to retrieve access tokens to authenticate a user. If I call the following method using a node-style callback, returned tokens is an object as I see in official examples:

oauth2client.getToken(code, function(err, tokens) {
    console.log(tokens.access_token);
    console.log(tokens.refresh_token);
});

When I wrap it in Q.ninvoke (in my app I'm trying to use promises everywhere, for self-teaching reasons), I get an array instead: the first element is the tokens object, the second is an object of type IncomingMessage:

Q.ninvoke(oauth2client, "getToken", code).then(function(tokens) {
    // Here tokens is:
    //
    // [ { access_token: 'XXXXXXX',
    //     token_type: 'Bearer',
    //     refresh_token: 'XXXXXXXXXXX',
    //     expiry_date: 1452516187132 },
    //   IncomingMessage {
    //     _readableState: 
    //      ReadableState {
    //        objectMode: false,
    //        highWaterMark: 16384,
    //        buffer: [],
    //        length: 0,
    //        pipes: null,
    //        pipesCount: 0,
    //        flowing: ... ... ... ... etc
});

Why? What am I missing? I tried wrapping standard node functions in Q.ninvoke, and the result is as expected, so I think it can be something with the Google library, and not related to Q, idk...

Upvotes: 0

Views: 451

Answers (1)

robertklep
robertklep

Reputation: 203419

oauth2client.getToken() apparently calls its callback with more than two arguments, in which case Q will gather all arguments (the ones after err) into an array that gets passed to the .then() callback (which only takes one argument).

You can use .spread() to spread these out into separate arguments again (and since you're only interested in the first, you can ignore the rest):

Q.ninvoke(oauth2client, "getToken", code).spread(function(tokens) {
  ...
});

Upvotes: 1

Related Questions