Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override javascript variable?

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.

like image 221
jolir Avatar asked Feb 10 '26 03:02

jolir


1 Answers

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);
  });
}
like image 119
relic Avatar answered Feb 12 '26 22:02

relic