从promisecallback更新对象字面值中的值的build议方法

我意识到有可能有10种方法来做到这一点,我通常会遇到一些笨拙的方式来实现它 – 但是我想得到一些关于“干净”的方式来更新对象字面值从承诺callback。

我目前的用例是:

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”(在这种情况下的callback)。 基本上我想要一个可以通过可能包含promise的函数对自己的值进行操作的单例。 我正在寻找更好的想法如何做到这一点。

是的,如果在对象文字中使用箭头函数,它不会将“this”绑定到对象。 所以在es2015中,可以使用对象文字的方法声明的简写语法 。 但是你希望在.then方法中使用箭头语法—它会将“this”绑定到封闭的上下文中:

 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); }); } }