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.