admin管理员组文章数量:1340287
I need to call a function that makes an http request and have it return the value to me through callback. However, when I try I keep getting null response. Any help?
Here is my code:
var url = 'www.someurl'
makeCall(url, function(results){return results})
makeCall = function (url, results) {
https.get(url,function (res) {
res.on('data', function (d) {
resObj = JSON.parse(d);
results(resObj.value)
});
}).on('error', function (e) {
console.error(e);
});
}
I need to call a function that makes an http request and have it return the value to me through callback. However, when I try I keep getting null response. Any help?
Here is my code:
var url = 'www.someurl.'
makeCall(url, function(results){return results})
makeCall = function (url, results) {
https.get(url,function (res) {
res.on('data', function (d) {
resObj = JSON.parse(d);
results(resObj.value)
});
}).on('error', function (e) {
console.error(e);
});
}
Share
Improve this question
asked May 31, 2013 at 16:05
RobRob
11.5k10 gold badges40 silver badges56 bronze badges
1 Answer
Reset to default 12You need to restructure your code to use a callback instead of returning a value. Here is a modified example that gets your external IP address:
var http = require('http');
var url = 'http://ip-api./json';
function makeCall (url, callback) {
http.get(url,function (res) {
res.on('data', function (d) {
callback(JSON.parse(d));
});
res.on('error', function (e) {
console.error(e);
});
});
}
function handleResults(results){
//do something with the results
}
makeCall(url, function(results){
console.log('results:',results);
handleResults(results);
});
本文标签: javascriptNodeJS function the returns http response valueStack Overflow
版权声明:本文标题:javascript - Node.JS function the returns http response value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743631563a2513196.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论