2017-04-04 26 views
1

我意識到有可能有10種方法來做到這一點,我通常絆倒一些笨拙的方式來實現它 - 但是我想得到一些關於「乾淨「從promise回調中更新對象字面值中的值的方法。建議的方法來更新從承諾回調對象字面值

我目前的使用情況是:

let groups2 = { 
    groupsList: [], 
    updateGroups:() => { 
     return axios({ 
      'url': 'https://gitlab.com/api/v3/groups?per_page=500', 
      'method': 'GET', 
      'headers': { 
       'private-token': GITLAB_API_PRIVATE_TOKEN, 
       'cache-control': 'no-cache' 
      } 
     }) 
     .then(function (response) { 
      console.log(response); 
      groups2.groupsList = response.data; 
     }) 
     .catch(function (error) { 
      console.log(error); 
     }); 
    } 
} 

這工作,但它 「感覺糟糕?」特別是從內部引用「groups2」(在本例中爲回調)。基本上,我想要一個可以通過可能包含承諾的函數對它自己的值進行操作的單例。我正在尋找更好的想法如何做到這一點。

回答

1

是的,如果您在對象文字中使用箭頭函數,它不會將「this」綁定到對象。所以在es2015中,您可以使用shorthand syntax for method declarations on object literals。但是你要使用箭頭語法.then方法內---那裏將綁定「本」的封閉的上下文:

let groups2 = { 
    groupsList: [], 
    updateGroups() { // Change this 
     return axios({ 
      'url': 'https://gitlab.com/api/v3/groups?per_page=500', 
      'method': 'GET', 
      'headers': { 
       'private-token': GITLAB_API_PRIVATE_TOKEN, 
       'cache-control': 'no-cache' 
      } 
     }) 
     .then((response) => { // and this 
      console.log(response); 
      this.groupsList = response.data; // and use the "this" variable here 
     }) 
     .catch(function (error) { 
      console.log(error); 
     }); 
    } 
} 
+0

完美,漂亮,乾淨 - 謝謝!我認爲我完全沒有意識到函數語法和箭頭語法之間有所不同。我只是把它們當作可互換的東西來對待。 – MPT