deniscapp
deniscapp

Reputation: 820

Reading data from Firebase with Node/Express

I am a beginner in the Node.JS/Express world, so I am here to ask for some help, in how to accomplish what I want.

I have this middleware which I am reading data from my database in Firebase, and pushing this data into an array of objects. My problem is: When can I use res.render, to render the view and send the data along? Because I always get the "Can't set headers after they are sent" error, and I know the reason, I just can't figure it out the best way to solve this.

exports.regulation = (req, res, next) => {
    const collisions = [];
    const collisionsRef = firebase.database().ref('/collisions').once('value').then((data) => {
        data.forEach((elem) => {
            // console.log(elem.val());
            const collision = {};
            collision.id = elem.getKey();
            collision.userId = elem.val().userId;

            const userRef = firebase.database().ref('/users/' + elem.val().userId).once('value').then((user) => {
                collision.user = user.val().name;
                collision.status = elem.val().status;
                collision.timestamp = elem.val().timestamp;

                collisions.push(collision);
                // console.log(collisions.length);
            }).catch((err) => {
                // next(err);
            });
        });

        // res.render('regulation', {collisions: collisions});    
    });
};

Thank you! :)

Upvotes: 2

Views: 3168

Answers (1)

Himani Agrawal
Himani Agrawal

Reputation: 1272

Request to firebase and res.render functions are to be run synchronously. Async.js library series function can be used to run functions synchronously.

const collisions = [];
function getData(callback) {

   const collisionsRef = firebase.database().ref('/collisions').once('value').then((data) => {
    data.forEach((elem) => {
        // console.log(elem.val());
        const collision = {};
        collision.id = elem.getKey();
        collision.userId = elem.val().userId;

        const userRef = firebase.database().ref('/users/' + elem.val().userId).once('value').then((user) => {
            collision.user = user.val().name;
            collision.status = elem.val().status;
            collision.timestamp = elem.val().timestamp;

            collisions.push(collision);
            // console.log(collisions.length);
        }).catch((err) => {
            // next(err);
        });
    });
    callback(null, 'one'); 
}

async.series([
    getData,
    function(callback) {
        res.render('regulation', {collisions: collisions});
        callback(null, 'two');
    }
]);

Upvotes: 1

Related Questions