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

Avoid forced callbacks

Avoid forced callbacks

Problem

I have a mongoose database query

var player;
Users.findById(req.user._id,function(err,user){     
    console.log('>>> user: '+user); //----2
    player = user;
    });
console.log('>>> player: '+player);    // ----1

in this code 1 executes before 2 because of 2 being inside a callback.

Is there a way to avoid this?

Problem courtesy of: laggingreflex

Solution

You have to create another function (lets say log) in the same namespace as player variable, put console.log('>>> player: '+player); to it and call log after you assigning player.

Thus, player variable is visible for both findById callback and log function.

Here is the code:

var player;
Users.findById(req.user._id,function(err,user){     
    console.log('>>> user: '+user);
    player = user;
    log();
});
function log() {
    console.log('>>> player: '+player);
}
Solution courtesy of: Curious

Discussion

View additional discussion.



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

Share the post

Avoid forced callbacks

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×