2

res.json(data) is called before redis client get data from server... How can i wait for data before send json object?

app.get('/api/player/:name', function(req, res) {
    var name = req.params.name;

    var data = {
        "connected": 0,
        "health": 0,
        "armour": 0
    };

    readClient.get(name + '.connected', function(err, value) {
        data.connected = value;
    });

    readClient.get(name + '.health', function(err, value) {
        data.health = value;
    });

    readClient.get(name + '.armour', function(err, value) {
        data.armour = value;
        console.log(data);
    });

    console.log(data);

    res.json(data);
});

1 Answer 1

1

Well, redis calls are async. That means that every query call must receive a callback function that shall be called once the query completes injecting data an errors. In order to send res.json when all data is ready then you must do something like:

app.get('/api/player/:name', function(req, res) {
    var name = req.params.name;

    var data = {
        "connected": 0,
        "health": 0,
        "armour": 0
    };

    var promises = [];

    promises.push( new Promise( function(resolve,reject) {
        readClient.get(name + '.connected', function(err, value) {
            if(err) { reject(err); }
            resolve(value);
        });
    } ) );

    promises.push( new Promise( function(resolve,reject) {
        readClient.get(name + '.health', function(err, value) {
            if(err) { reject(err); }
            resolve(value);
        });
    } ) );

    promises.push( new Promise( function(resolve,reject) {
        readClient.get(name + '.armour', function(err, value) {
            if(err) { reject(err); }
            resolve(value);
        });
    } ) );

    Promise.all(promises).then( function(values) {
        console.log(values);
        data.connected = values[0];
        data.health = values[1];
        data.armour = values[2];
        res.json(data);
    } ).catch(handleError);
});

function handleError(err) {
    res.status(501); 
    res.send({msg:err.message});
}

I'd recommend working with await and Promises however, but this is a good starting point.

Hope this helps

Sign up to request clarification or add additional context in comments.

3 Comments

Ok this work! Can you show me how do that with async/await and Promises?
Ok. Could you pleas mark the answer as correct? (click on the green "tick" sign)
There you go. I've changed my answer to show how to solve it with promises and vanilla javascript. A more elegant solution would be using ECMASCRIPT6 with lambdas. But I don't know if you're familiarized with it

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.