2

I am having trouble returning JSON from an HTTP GET request using Node.JS.

Reading through examples and documentation, this is what I have come up with:

var http = require('http');

var options = {
    host: 'some.host.com',
    path: '/some/path'
};

var callback = function(response) {
    var raw = '';
    response.on('data', function(d) {
    raw += d;
    });
    response.on('end', function() {
    var data = JSON.parse(raw);
    });
    return data;
};

http.request(options, callback).end()

I have also tried returning data from inside the response.on scope without any luck. Note that with CURL I can get data without a problem.

What am I doing wrong and how can I fix the above code to get the JSON?

0

1 Answer 1

2

You can never return a value from a callback.

If you get a value in a callback, you need to use another callback to extract the value or use it on the spot: you cannot return it. The question is always "okay now that I have this data, what do I want to do with it?" and the answer "return it" is not acceptable.

For example, this should work:

var http = require('http');

var options = {
    host: 'some.host.com',
    path: '/some/path'
};

var useData = function(data) {
    // do something
}

var callback = function(response) {
    var raw = '';
    response.on('data', function(d) {
        raw += d;
    });
    response.on('end', function() {
        var data = JSON.parse(raw);
        useData(data);
    });
};

http.request(options, callback).end()

(Also, not your primary problem, but you have two variables named data: one local in var data line, and another global one in return.)

EDIT:

I'm quite confused why I can't "return" a value from a callback. Don't functions have return values/variables, or evaluate to a value?

They do, but it's too late. Analogy time.

Synchronous:

Martha tells John to answer the phone, then waits patiently for the conversation to finish. She then asks him who it was and what they wanted. John says their neighbour is asking for a cup of sugar. She tells him to go and give a cup of sugar to their neighbour. Then, she goes out to meet her friends.

var reply = john.answerPhone();
var action = reply.figureOutResponse();
john.tellToDo(action);

Wrong asynchronous:

Martha tells John to answer the phone, and tell her what it is, then goes out to meet her friends. She tries to process the reply as heard from John as soon as she leaves the house - but John hasn't even picked up the receiver yet, let alone told her anything - so she has a nervous breakdown. If she had tried to read the note, it's still a blank piece of paper (even if we ignore the fact that it is probably still at the house), so she has another breakdown. If anyone still cares, five minutes later John hangs up and announces the fact that his neighbour needs sugar to the empty house, since Martha is not there any more. Just in case, he also writes her a note. No-one telling him what else to do, he picks up newspaper and starts wasting time. The note never gets read.

var note;
var reply = john.answerPhone(function(reply) {
    note = reply;
    return reply;
};
note.figureOutResponse();
// Cannot read property 'figureOutResponse' of undefined
reply.figureOutResponse();
// Cannot read property 'figureOutResponse' of undefined

Correct asynchronous:

Martha tells John to answer the phone, and call her back with the info since she has to go out to meet with friends. She goes out, and John picks up the phone. Five minutes later, John calls Martha's cellphone to say that it was a neighbour looking for some sugar. She tells him to fill up a cup and give it to the neighbour, then hangs up and continues her bus ride.

var marthasCellphone = function(data, respondCallback) {
    var action = data.figureOutResponse();
    respondCallback(action);
}
john.answerPhone(function(data) {
    // callback here: no returns, pass data on to another callback
    var action = marthasCellphone(data, function(action) {
        // another callback here; use action immediately
        john.tellToDo(action);
    });        
});
reply.figureOutResponse();
Sign up to request clarification or add additional context in comments.

3 Comments

I'm quite confused why I can't "return" a value from a callback. Don't functions have return values/variables, or evaluate to a value?
Also, I mainly just want to write the JSON to a global variable so that I can see the JSON in the REPL.
Thanks, I figured it out.

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.