0

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.

3
  • 4
    Say hello to callback hell – callbackhell.com Commented May 7, 2016 at 10:44
  • 2
    You should check out packages like async and Promises to help you out of callback hell. Commented May 7, 2016 at 10:45
  • @BlazeSahlzen thanks! Commented May 7, 2016 at 10:57

1 Answer 1

2

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.

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

Comments

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.