带请求范围的coffeescript

request = require('request') auth = url: '' method: 'POST' json: credentials: username: "" key: "" exports = exports ? this request auth, (err, res, body) -> exports.inside = body console.log(exports.inside) 

然后上面是Coffeescript和Node.js的请求模块。 我不知道如何获取请求函数内的数据。 这是我申请的主要障碍。

谢谢!

**编辑**

瓦迪姆巴里舍夫的代码更新做到了! 非常感谢 :) !

您正尝试在request函数callback中分配之前输出exports.inside 。 由于requestfunction是asynchronous的。 你可以通过callback或事件来获得这个函数的结果。

更新

 request = require('request') exports = exports ? this getAuth = (callback) -> auth = url: '' method: 'POST' json: credentials: username: "" key: "" request auth, (err, res, body) -> exports.inside = body callback err, body getAuth (err, body) -> # here is exports.inside ready console.log exports.inside # also you can access body and request error arguments here # body === exports.inside here # err is request error (is null/undifined if request is successful) 

一旦请求函数完成,它将触发一个callback函数,这是唯一可以可靠地访问“body”值的地方。

你遇到的问题是,当console.log函数运行时,callback没有被触发,因为请求没有完成。

查看在nodejs中使用fs.stat的问题,以获得asynchronous编程环境中对程序stream的更有说服力的描述。

—编辑—用例子:

考虑一下:

 1: path='/tmp/file.txt' 2: result='' 3: fs.readFile path, (err,data) -> 4: throw err if err 5: result=data 6: console.log result 

如果我们要跟踪这个操作,我们会发现执行的顺序是1,2,3,6,… 4,5,其中,由于disc I / o的性质,省略号表示一些未知量的时间。

因为读取操作需要一些时间才能完成,而不是等待结果,所以我们提供了一个callback函数,在将来文件的内容被读取时,这个callback函数将会在某个不可预知的地方被调用,因此可以被分配给'结果'。

当程序stream程到达第6行时,由于文件读取操作没有完成,所以没有调用callback,所以结果没有被设置。

这是asynchronous编程的本质,而不是在等待操作完成之前完成,我们可以把浪费的时间用于其他目的。

— 2ND编辑—好的,根据你的要求,这里是你的例子修改,以便它的工作。

 request = require('request') auth = url: '' method: 'POST' json: credentials: username: "" key: "" exports = exports ? this request auth, (err, res, body) -> exports.inside = body console.log(exports.inside) 

请注意,正如现在已经描述过的那样,您不能在callback之外访问请求的结果,因为您无法知道请求何时完成。