Javascript 如何重写此承诺链以避免需要多个函数?
我刚开始使用mobx和react(顺便说一句,这是一个很棒的团队!),我的商店有点问题。我想从现有API异步获取一些数据,然后使用这些数据更新我的存储中的一些现有观测值:Javascript 如何重写此承诺链以避免需要多个函数?,javascript,node.js,fetch,es6-promise,mobx,Javascript,Node.js,Fetch,Es6 Promise,Mobx,我刚开始使用mobx和react(顺便说一句,这是一个很棒的团队!),我的商店有点问题。我想从现有API异步获取一些数据,然后使用这些数据更新我的存储中的一些现有观测值: class StationStore { @observable stations = [] loadStations() { fetch('http://localhost:3000/api/station/getStations') .then(function(response) { retu
class StationStore {
@observable stations = []
loadStations() {
fetch('http://localhost:3000/api/station/getStations')
.then(function(response) { return response.json() })
.then(stations=>this.parseStations(stations));
}
@action parseStations(stations) {
var newStations = stations.map((station)=>{
let s = new Station;
s.id=station.id;
s.name=station.Text;
s.deviceType=station.DeviceType;
return s;
});
this.stations.replace(newStations);
}
}
如您所见,我需要将逻辑划分为两个单独的函数,以便能够访问this.stations
。我试图将映射和替换零件包含到加载站()
的second-then()中,但当我这样做时,我无法访问我的存储,因为其中未定义此项
如何修复此问题?使用
var self=this代码>应该可以解决您的问题
class StationStore {
@observable stations = [];
loadStations() {
var self = this;
fetch('http://localhost:3000/api/station/getStations')
.then(function (response) {
return response.json()
})
.then(stations => {
self.stations.replace(stations.map((station) => {
let s = new Station;
s.id = station.id;
s.name = station.Text;
s.deviceType = station.DeviceType;
return s;
}));
});
}
}
使用箭头函数,以便定义this
。如何在加载站()的第二个中调用this.parseStations(stations)
。然后()
如果中未定义此
,则无需引入self
变量。您还丢失了动作包装器