Dharmesh7980 Dharmesh7980 - 1 year ago 58
Node.js Question

Get variable of function within in same file in node.js

i tried with this code but i can't get value of variable


var haveemail = 0;

collection.count({email: req.body.email}, function (error, count,callback) {
console.log(count);
haveemail = count;
});
console.log(haveemail)

Answer Source

Node.js works asynchronously, which means that right after collection.count() starts running, your console.log() call starts, most probably before the count call ends and before your variable is set.

you should move the console.log call to inside the callback, to make sure it happens after haveemail variable is set:

var haveemail = 0; 

collection.count({email: req.body.email}, function (error, count,callback) 
{ 
    console.log(count); 
    haveemail = count; 
    console.log(haveemail);
});