Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js async consistency

Node.js async consistency

Problem

I have the following code :

server.use(function(req, res, next) {
    users_db.set(req.user, function(err) { // async call to mongodb
        if (err) {
          console.error(err);
        }
      });
    }
    return next();
});

server.get('/', function(req, res) {
    req.user.active = true; // this is a new field in user object
    res.send(req.user);
    }
});

So, As you see, when users_db.set() is called, req.user doesn't have the active=true field. It is being inserted only in the server.get() function.

Is it possible that user.active = true is registered in the db nevertheless because of the asynchronous nature of the call ?

Problem courtesy of: Michael

Solution

As far as I know (it is like that in Express at least) .get method accepts many middleware functions. So I guess that the following will work:

server.get(
    '/', 
    function(req, res, next) {
        req.user.active = true; // this is a new field in user object
        res.send(req.user);
        next();
    },
    function(req, res, next) {
        users_db.set(req.user, function(err) { // async call to mongodb
            if (err) {
              console.error(err);
            }
          });
        }
        return next();
    }
);

Doing the things like that you are sure that req.user.active is populated always before to reach the moment with users_db.set.

Solution courtesy of: Krasimir

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js async consistency

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×