Node.JS function the returns http response value
12,453
You 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.com/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);
});
Author by
Rob
Updated on June 05, 2022Comments
-
Rob almost 2 years
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.com' 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); }); }
-
Rob almost 11 yearsThanks However, this function does exactly the same thing my sample does. My sample also works with console.log. I need to get a result RETURNED by calling the function. Take this for example
hi = function(a, b) {c = "hi"return b(c)};
When I executehi('string',function(bb){return bb})
I am returned "hi" as a result of calling the function. Hope this makes sense -
mr.freeze almost 11 yearsYour example is trying to return a value from an async callback. That won't work. You need to use the value in the callback instead of returning it.
-
Rob almost 11 yearsOk, I understand. Is there any way to get that value out of the callback function and use in another function executed at the same time? I know this is a bit wonky. Appreciate the help
-
mr.freeze almost 11 yearsSure, just call your target function and pass results as a parameter. I will update the example to reflect that.