ES6:如何使用 "this" 和 fetch?
ES6: How to use, "this", with fetch?
我已经阅读了大量关于 ES6 的文档以及随之发生的变化。我正在尝试将新的 oop 语法与一些新的库(如 fetch)结合起来。所以这是我的代码:
apiCall(url, thisAlias=this){
fetch(url).then(function(response){
return response.json();
})
.then(function(respObj){
thisAlias.domUpdater(respObj);
});
}
这是一个基础 class,它有一个继承的 class,最终将有许多继承的 class。我的想法是使用 fetch 进行通用 api 调用,我可以根据继承 class 更改 domUpdater 方法。我花了很多时间让这段代码工作,为 this 关键字设置别名,以便它可以在 fetch 调用中使用。有没有更优雅的方法来做到这一点?我似乎无法直接将其作为参数传递。
使用具有词法 this
的 arrow functions 将最大程度地帮助您处理这段特定的代码
apiCall (url) {
fetch(url).then(
response => response.json()
).then(
respObj => this.domUpdater(respObj)
).catch(
err => console.error(err.message, err)
)
}
否则,如果你可以使用更新的 async
/await
,你根本不必担心 this
指向错误的东西——即使没有箭头功能。
<b>async</b> apiCall (url) {
try {
let response = <b>await</b> fetch(url);
this.domUpdater(response.json());
}
catch (err) {
console.error(err.message, err);
}
}
我已经阅读了大量关于 ES6 的文档以及随之发生的变化。我正在尝试将新的 oop 语法与一些新的库(如 fetch)结合起来。所以这是我的代码:
apiCall(url, thisAlias=this){
fetch(url).then(function(response){
return response.json();
})
.then(function(respObj){
thisAlias.domUpdater(respObj);
});
}
这是一个基础 class,它有一个继承的 class,最终将有许多继承的 class。我的想法是使用 fetch 进行通用 api 调用,我可以根据继承 class 更改 domUpdater 方法。我花了很多时间让这段代码工作,为 this 关键字设置别名,以便它可以在 fetch 调用中使用。有没有更优雅的方法来做到这一点?我似乎无法直接将其作为参数传递。
使用具有词法 this
的 arrow functions 将最大程度地帮助您处理这段特定的代码
apiCall (url) {
fetch(url).then(
response => response.json()
).then(
respObj => this.domUpdater(respObj)
).catch(
err => console.error(err.message, err)
)
}
否则,如果你可以使用更新的 async
/await
,你根本不必担心 this
指向错误的东西——即使没有箭头功能。
<b>async</b> apiCall (url) {
try {
let response = <b>await</b> fetch(url);
this.domUpdater(response.json());
}
catch (err) {
console.error(err.message, err);
}
}