1

I have a thunk called logInline (adapted from the Co documentation).

I notice the thunkified get always seems to yield an array. Is this by design? Is it thunkify doing this, or is it a standard part of yield?

var co = require('co'),
  get = thunkify(request.get);

var logInline = co(function *(){
  var google = yield get('http://google.com'); 
  console.log(google[0].statusCode);
})

logInline()

Note the variable 'google' here is always an array. Why? Note that request.get normally returns err, response (ie, there are no arrays).

The script, BTW, returns 200 or whatever other response code google.com returns.

Alas the yield documentation is pretty sparse ATM.

Edit: Thunks don't always return arrays. Eg if var readFile = thunkify(fs.readFile);:

var fileContents = yield readFile('myfile', 'utf8');
log(fileContents);

In this case, fileContents is not returned inside an array. So why was google inside an array? There seems to be something in thunkify controlling what the thunks return

Community
  • 1
  • 1
mikemaccana
  • 81,787
  • 73
  • 317
  • 396
  • 1
    It is just a guess as I didn't have time to look at `yield` and `thunkify`, but there is a similar behavior with `when` and `node.lift`. As the callback method that is _wrapped_ by it could have (beside the `err`) more then one argument, the result is always an array where `a[0]` is the first argument, `a[1]` the second, ... – t.niese Apr 11 '14 at 14:19

1 Answers1

5

I notice the thunkified get always seems to yield an array. Is this by design?

I don't know and cannot confirm, as you say the docs (of co, yield is not of interest here) are quite sparse.

I could however image that the yield does result in the arguments-array of the callback, to easily support multiple return values. You might use a destructuring assignment to get the single results back:

co(function *(){
  var [google] = yield get('http://google.com'); 
  console.log(google.statusCode);
})

Edit:

There seems to be something in thunkify controlling what the thunks return

Indeed, this happens only sometimes. I now checked the code, which reads

if (arguments.length > 2) res = slice.call(arguments, 1);

so if the callback function (of the thunkified call, but imagine it to be the one that is passed to fs.readFile or request.get directly) is called with more than one result argument (the error parameter is ignored), then an array will be yielded to your generator code.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • 2
    Thanks, it looks like destructuring assignment is still on the way in Node ATM (http://stackoverflow.com/questions/17379277/destructuring-in-node-js) so I currently do `var google = (yield get('http://google.com'))[0];` – mikemaccana Apr 11 '14 at 14:39
  • Aww, I had expected them to work… FF does support them for so long :-/ – Bergi Apr 11 '14 at 14:48