Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何重写此承诺链以避免需要多个函数?_Javascript_Node.js_Fetch_Es6 Promise_Mobx - Fatal编程技术网

Javascript 如何重写此承诺链以避免需要多个函数?

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

我刚开始使用mobx和react(顺便说一句,这是一个很棒的团队!),我的商店有点问题。我想从现有API异步获取一些数据,然后使用这些数据更新我的存储中的一些现有观测值:

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
变量。您还丢失了动作包装器