Andremoniy Andremoniy - 4 months ago 13
Javascript Question

Preserve variable's value for $http.get async result processing

Let us consider that we have a function, invoked on some event (let's say -

scroll
event). This function loads more items into some list.

Suppose that the logic of this function is designed as follows:

function() {
oldSize = list.length;

// add new items (prepare them in advance)
for (i = 0; i < PAGE_SIZE; i++) list.push({});

$http.get("/next/page/" + oldSize).then(function() {
// here I want operate with oldSize value which is actual on moment of
// the $http.get invocation:
for (i = 0; i < PAGE_SIZE;i++) {
// do something with
list[oldSize + i] = ... ;
}
}
}


The problem is that the entire function can be invoked almost simultaneously multiple times, what leads to the effect, that
.then(function() {
operates with improper value of
oldSize
variable - it becomes the value of last
list.length
, while I need it be preserved as it was on the moment of invocation.

For instance, if this event listener was invoked almost simultaneously 2 times, it will be:


  1. oldSize == 5
    , list increased by 10 (for example) elements. But inside
    $http.get(...).then()
    I need to work with value
    oldSize == 5
    .

  2. Second invocation:
    oldSize == 15
    (because we have increased list by 10 elements in the first invocation). So inside this particular
    $http.get(...).then()
    I want to have
    oldSize == 15
    .



I hope it is clear. Please, do not suggest me to change my logic. I just want to know how to save variable value for postponed result of the asynchronous function (in my case it is
$http.get(...).then(...)
). Thanks.

Answer Source

Assuming you are not able to define oldSize inside this function because you need it somewhere else.

function() {
    oldSize = list.length;

    // add new items (prepare them in advance)
    for (i = 0; i < PAGE_SIZE; i++) list.push({});


    var currentOldSize = oldSize;

    $http.get("/next/page/" + oldSize).then(function() {
       // here I want operate with oldSize value which is actual on moment of 
       // the $http.get invocation:
       for (i = 0; i < PAGE_SIZE;i++) {
          // do something with 
          list[currentOldSize + i] = ... ;
       }
     }
}