2

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);
                });
        }

1 Answer 1

12

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);        
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks 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 execute hi('string',function(bb){return bb}) I am returned "hi" as a result of calling the function. Hope this makes sense
Your 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.
Ok, 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
Sure, just call your target function and pass results as a parameter. I will update the example to reflect that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.