简体   繁体   English

为什么thunkify / yield总是返回一个数组?

[英]Why does thunkify / yield always return an array?

I have a thunk called logInline (adapted from the Co documentation ). 我有一个thunk称为logInline(改编自合作文件 )。

I notice the thunkified get always seems to yield an array. 我注意到,经过改进的get似乎总是yield一个数组。 Is this by design? 这是设计使然吗? Is it thunkify doing this, or is it a standard part of yield ? 这样做是不是很thunkify ,还是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. 请注意,此处的变量“ google”始终是一个数组。 Why? 为什么? Note that request.get normally returns err, response (ie, there are no arrays). 请注意, request.get通常返回err, response (即,没有数组)。

The script, BTW, returns 200 or whatever other response code google.com returns. 脚本BTW返回200或google.com返回的其他任何响应代码。

Alas the yield documentation is pretty sparse ATM. 遗憾的是,收益文档非常稀疏。

Edit: Thunks don't always return arrays. 编辑: Thunk并不总是返回数组。 Eg if var readFile = thunkify(fs.readFile); 例如,如果var readFile = thunkify(fs.readFile); :

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

In this case, fileContents is not returned inside an array. 在这种情况下,fileContents不会在数组内返回。 So why was google inside an array? 那么,为什么Google会放在数组中? There seems to be something in thunkify controlling what the thunks return thunkify中似乎有些东西控制着thunks返回

I notice the thunkified get always seems to yield an array. 我注意到,经过改进的get似乎总是产生一个数组。 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. 我不知道,也无法确认,正如您所说的(公司, yield在这里不重要)文档非常稀疏。

I could however image that the yield does result in the arguments-array of the callback, to easily support multiple return values. 但是,我可以想象出yield确实会导致回调的arguments-array,以轻松支持多个返回值。 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 thunkify中似乎有些东西控制着thunks返回

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 yield ed to your generator code. 因此,如果使用多个结果参数(忽略了error参数)调用了回调函数(经过thunkified调用,但想像它是直接传递给fs.readFilerequest.get函数),则该数组将yield您的生成器代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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