Variable has different values inside and outside a function

176 views Asked by At

I'm trying to set the value of an ID in the variable newID. To "fill" the variable I'm reading a model like this:

press: function() {
    var newID = 0;
    oModel.read("/Delivery", null, null, true, function(oData) { 
        newID = oData.results[oData.results.length - 1].ID;                   
        console.log(newID);

    }
    console.log(newID);
}

The first console.log gives me the value that I want, but the second one gives me 0 (the first condition set). I've tried using the incremental operator += and using this.newID but all in vain.

It really is a silly problem, probably something the way I'm calling newID on the console or the way I increment it inside the function...

Thanks in advance.

1

There are 1 answers

1
ecarrizo On BEST ANSWER

This was going to be a comment but it is so huge, so take it as a comment:

It is possible that the oModel.read function is asynchronous so when you execute the code basically that happen is this:

1) You declare the variable as 0.

2) You execute read function.

3) You execute console.log(var) => this print 0. (Because read does not finished yet and it is still 0 at this point).

4) Read function finished it work assign the desired value to var and execute console.log(var) => this print the desired value.

If that is the case you can implement something like this:

var press = function() {
    var newId = 0;
    function callback() {
       console.log(newId); 
    }
    oModel.read("/Delivery", null, null, true, function(oData) {
        newID = oData.results[oData.results.length - 1].ID;                   
        console.log(newID);
        callback();
   }
}