I am working on an Express.io mini project and I am stuck on this variable override problem.
Here is my code:
get_time_offset = function(timezone_id){
Timezone.findById(timezone_id, function(err, doc){
if(err) {
console.log(err);
} else {
console.log(doc.offset);
}
});
}
This code block can display the doc.offset's value through the console.log without any problem and I would like to make the doc.offset be available outside the Timezone Object. Here's what I have come up so far:
get_time_offset = function(timezone_id){
var offset;
Timezone.findById(timezone_id, function(err, doc){
if(err) {
console.log(err);
} else {
offset = doc.offset;
}
});
console.log(offset);
}
It says 'offset is undefined' and I can't seem to find any other way of solving this.
I'm thinking either change your initial declaration to...
var offset = {};
...or, your console.log is executing before your function has finished. Simple check by adding a log inside the function...
} else {
offset = doc.offset;
console.log('from inside ... ', offset);
}
});
}
console.log('from outside ... ', offset);
... and see if 'outside' fires first.
EDIT:
If 'from outside' is running first, have your follow-up code called by the initial function.
get_time_offset = function(timezone_id){
var offset;
function processResult(val) {
console.log(val);
}
Timezone.findById(timezone_id, function(err, doc){
if(err) {
console.log(err);
} else {
offset = doc.offset;
}
processResult(offset);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With