Javascript 从promise回调更新对象文本中的值的建议方法
我意识到可能有10种方法可以做到这一点,我通常会遇到一些笨拙的方法来实现这一点——不过,我想了解一些“干净”的方法,来从承诺回调更新对象文本中的值 我当前的用例是:Javascript 从promise回调更新对象文本中的值的建议方法,javascript,node.js,promise,Javascript,Node.js,Promise,我意识到可能有10种方法可以做到这一点,我通常会遇到一些笨拙的方法来实现这一点——不过,我想了解一些“干净”的方法,来从承诺回调更新对象文本中的值 我当前的用例是: let groups2 = { groupsList: [], updateGroups: () => { return axios({ 'url': 'https://gitlab.com/api/v3/groups?per_page=500',
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中,您可以使用。但是您需要在
方法中使用箭头语法。然后方法将“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);
});
}
}
完美,漂亮,干净-谢谢!我认为我没有完全理解函数语法和箭头语法之间的区别。我只是把它们当作可以互换的。