Neil
Neil

Reputation: 2519

NodeJS + Socket.IO can't get json to return

I'm using Socket.IO, AngularJS, Request, and Express and I am trying to pull in some data from a request and then send it off to the client. Here are my functions:

    var getJsonFromJsonP = function (url, callback) {
        request(url, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var jsonpData = body;
                var json;
                try {
                   json = JSON.parse(jsonpData);
                }
                catch(e) {
                    var startPos = jsonpData.indexOf('({');
                    var endPos = jsonpData.indexOf('})');
                    var jsonString = jsonpData.substring(startPos+1, endPos+1);
                    json = JSON.parse(jsonString);
                }
                callback(null, json);
            } else {
                callback(error);
            }
        })
    }

    var getScoring = function() {
        var url = 'http://live.nhle.com/GameData/RegularSeasonScoreboardv3.jsonp';
        var dataReturn;
        getJsonFromJsonP(url, function (err, data) {
            console.log(data);
            return data;
        });
    }

    io.sockets.on('connection', function(socket) {
        socket.emit('init', { data: getScoring() });
    });

The getJsonFromJsonP solution is from another post, and it is producing ok results.

The console.log(data) shows the correct data in the backend, but the client (AngularJS) is not getting it. If I change return data to return 'hello world' the 'hello world' appears in the client as { data : 'hello world' }.

Upvotes: 1

Views: 2127

Answers (1)

gherkins
gherkins

Reputation: 14983

The getScoring() function uses the getJsonFromJsonP(), which is asynchronous (as it has to wait for the request).

So you might also want to pass getScoring() a callback function, then emit the event in that callback. Like this for example:

var getScoring = function(callback) {
    var url = 'http://live.nhle.com/GameData/RegularSeasonScoreboardv3.jsonp';
    var dataReturn;
    getJsonFromJsonP(url, function (err, data) {
        //pass data to callback function
        callback(data);
    });
}

io.sockets.on('connection', function(socket) {
    getScoring( function(data){
        socket.emit('init', { data: data });
    });
});

otherwise you won't be able to return anything because you are already out of the scope when you have the data. You can log it to the console, but not return it.

Upvotes: 1

Related Questions