简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM