lilly
lilly

Reputation: 701

Asynchronous callbacks in JavaScript

PHP dev here, I'm wrestling with NodeJS for a while and I still can't wrap my head around the idea of asynchrony is JS/Node.

Look at this (ExpressJS):

router.get('/:id', function (req, res, next) {
    var id = req.params.id;
    var db = new Firebase('some_firebase_db');
    db.child("users/"+id).once('value', function (snapshot) {
        var user = snapshot.val();
        if (user) {
            db.child("messages/"+id).once('value', function (snapshot) {
                res.render('user/messages', {
                    'user': user, 
                    'messages': snapshot.val()
                });
            });
        } else {
            res.render('404');
        }
    });
});

To make database value accessible for a res object I need to render views inside the fetching data callbacks.

So when I need, say, make 6 requests to my DB I will have to embed my res object in 6 callbacks?

Or is there different approach that will make the code more readable keeping it asynchronous?

Ultimately, I need a way to fetch data from db multiple times in one request that will not make my code look like Christmas tree.

Upvotes: 0

Views: 123

Answers (1)

t.niese
t.niese

Reputation: 40842

You can make it more readable even without using async or Promise:

router.get('/:id', function(req, res, next) {
  var id = req.params.id;
  var db = new Firebase('some_firebase_db');

  db.child("users/" + id).once('value', userResult);

  function userResult(snapshot) {
    var user = snapshot.val();
    if (user) {
      db.child("messages/" + id).once('value', messageResult);
    } else {
      res.render('404');
    }
  }

  function messageResult(snapshot) {
    res.render('user/messages', {
      'user': user,
      'messages': snapshot.val()
    });
  }
});

But using async or Promise would be a better solution.

Upvotes: 2

Related Questions