How to override javascript variable?

I am working on an Express.io mini-project and I am stuck with this problem of variable overriding.

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 value of doc.offset via console.log without any problems, and I would like to make doc.offset accessible outside the Timezone object. Here is what I have come up with 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 that "offset is undefined" and I cannot find another way to resolve this issue.

+3
source share
3 answers

I think either we’ll change your initial ad to ...

var offset = {};

... or, your console.log is executed until your function completes. A simple check by adding a log inside a function ...

    } else {
      offset = doc.offset;
      console.log('from inside ... ', offset);
    }
   });
  }
console.log('from outside ... ', offset);

... , "".

EDIT:

"", .

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);
  });
}
+3

, , http://thomasdavis.imtqy.com/tutorial/anonymous-functions.html

var scope = {offset : 10};
get_time_offset = function(timezone_id){
    Timezone.findById(timezone_id, function(err, doc, scope){
        if(err) {
            console.log(err);
        } else {
            scope.offset = doc.offset;
        }
    });
}
console.log(scope.offset);

, : offset , , http://jsfiddle.net/VLbVw/4/

+2

Try the following:

get_time_offset = function(timezone_id, callback){

    Timezone.findById(timezone_id, function(err, doc){
       if(err) {
            console.log(err);
    callback(false);
       } else {
         callback(doc.offset);
       }
    });

};

get_time_offset(5, function(offset){
   console.log(offset)
});
0
source

All Articles