[英]Callback on node.js http REST call issue
Have a following node.js call to http get REST API. 通过以下node.js调用http获得REST API。 When I run it, it returns the JSON result.
当我运行它时,它返回JSON结果。 However, I am trying to get the result to
console.log
on var r
after assigning the result. 但是,我试图在分配结果后将结果发送到
var r
上的console.log
。 Why do I always get undefined
? 为什么我总是变得
undefined
? Looks like I am messing up the javascript scope. 看来我搞砸了javascript范围。 Any help is appreciated.
任何帮助表示赞赏。
var http = require('http'),
oex_appId = 'myappId',
_hostname = 'openexchangerates.org',
_path = '/api/latest.json?app_id=' + oex_appId;
var r;
function getRates(cb) {
var options = {
hostname: _hostname,
path: _path,
method: 'GET'
};
var responseCallback = function(response) {
var latestRates = '';
var parseCurrencies = function(rates) {
var currencies = JSON.parse(rates);
currencies.rates['USD'] = 1;
return currencies.rates;
};
response.setEncoding('utf8');
response.on('data', function(chunk) {
latestRates += chunk;
}).on('error', function(err) {
throw new Error(err);
}).on('end', function() {
cb(parseCurrencies(latestRates));
});
};
var req = http.request(options, responseCallback);
req.on('error', function(e) {
throw e;
});
req.end();
};
var d = function(data) {
console.log(data["INR"]);
currencies["INR"].amount = data["INR"];
r = data;
};
getRates(d);
console.log(r);
Why do I always get undefined?
为什么我总是不确定?
Your problem is not an scope issue but a misunderstanding of async execution. 您的问题不是范围问题,而是对异步执行的误解。 In this code you are printing the value of r before it is assigned.
在此代码中,您将在赋值前打印r的值。
The execution of your code is as follow: 您的代码执行如下:
In general, you cannot expect the next line to have a value that will be assigned via an async callback. 通常,您不能期望下一行具有将通过异步回调分配的值。 Instead you should reference the value inside the callback.
相反,您应该在回调中引用该值。 In your case you should move the console.log(r) inside your callback function d.
在您的情况下,应将console.log(r)移动到回调函数d中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.