2017-06-20 51 views
0

让我们考虑一下我们有一个函数,在某个事件(例如 - scroll事件)上调用。该功能将更多项目加载到某个列表中。

假设这个函数的逻辑设计如下:

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] = ... ; 
     } 
    } 
} 

的问题是,整个功能可几乎同时多次调用,什么导致了作用,即.then(function() {不当值运行的oldSize变量 - 它成为最后list.length的值,而我需要它被保留,因为它是在调用的时刻。

例如,如果该事件监听器被调用几乎同时的2倍,这将是:

  1. oldSize == 5,列表增加10(例如)元素。但在$http.get(...).then()里面,我需要使用价值oldSize == 5

  2. 第二次调用:oldSize == 15(因为我们在第一次调用时增加了10个元素的列表)。所以在这个特别是$http.get(...).then()我想有oldSize == 15

我希望它很清楚。请不要建议我改变我的逻辑。我只想知道如何为异步函数的推迟结果保存变量值(在我的情况下,它是$http.get(...).then(...))。谢谢。

+0

为什么在外部范围中定义'oldSize'? –

+0

@YuryTarabanko如果我需要在调用get方法之前保存它的值,我应该在哪里定义它? – Andremoniy

+0

如果你不在这个函数之外使用它(和嵌套的回调函数),你可以简单地使用'var oldSize = list.length'。否则,请查看下面的答案。 –

回答

1

假设您无法在此函数内定义oldSize,因为您在其他位置需要它。

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] = ... ; 
     } 
    } 
} 
1

为什么oldSize对外宣称的范围或全球范围内?在该函数的范围内声明该变量。

let list = []; 

function() { 
    let size = list.length; 

    $http.get(...) 
     .then(function() { 
      // handle size 
      [...] 
     }); 
};