0

I have this problem, when I change the value of a variable inside my function if i want to use it outside of it, the vaalue of the variable returns to 0, but inside of it, the value it's changed.

I need to know a way to keep the value of the variable outside the function.

Here is my current code:

function getCarsWithNoStatus() {
   var statusName = [];
 // We set the total counters for the areas
   var totals = {bodyshop: 0, paintshop: 0, assembly: 0};
 // var tmpTotal = 0;


        WebApiFactory.getNoStatusOrders(bodyShop1).then(function(statusMonData) {
            for(var statusProperty in statusMonData.NoStatusOrders) {
                statusName = statusProperty;
                for (var j = 0; j < statusMonData.NoStatusOrders[statusName].length; j++) {
                    if (typeof statusMonData.NoStatusOrders[statusProperty][j] !== null) {
                        totals.bodyshop++;
                        console.log(totals.bodyshop); //here shows correct value
                    }
                }
            }
        });
        console.log(totals.bodyshop); //value returns to 0

  }

1 Answers1

0

The value of totals is being modified in an asynchronous code, so your console.log is being executed before the asynchronous code is finished. When working with such code you usually want to return a Promise or execute a callback after the async code is finished executing.

shawon191
  • 1,945
  • 13
  • 28