从 promise 回调更新对象文本中的值的建议方法



我意识到可能有 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"感觉很糟糕?"(在这种情况下在回调中)。本质上,我想要一个单例,它可以通过可能包含承诺的函数对自己的值进行操作。我正在寻找有关如何做到这一点的更好想法。

是的,如果您在对象文本中使用箭头函数,它不会将"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);
});
}
}

最新更新