javascript - 如何重写这个 promise 链以避免需要多个函数?

标签 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) { 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。我尝试将 map 和替换部分包含到 loadStations() 的第二个 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;
                }));
            });
    }
}

关于javascript - 如何重写这个 promise 链以避免需要多个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44415512/

相关文章:

php - 表的奇数行和偶数行

javascript - NodeJS 将数组放入 MongoDB doc.validate 不是函数

javascript - 如何检测与 puppeteer 一起使用的 chrome 版本?

react-native - 从 react native 获取调用中获取文本

php - 通过外键获取 MySQL

javascript - 尝试追加到使用 Backbone 创建的表

javascript - LitElement 不会为原生 Web 组件设置 textContent

node.js - 使用 switch case 更新集合中的多个文档

javascript - Angular2 - 环回 - 安全实现

javascript - 如何发送像表单数据 postman 这样的值 - React js