如何将数据导出到另一个模块

时间:2018-04-09 08:08:48

标签: javascript npm webpack ecmascript-6 module

我有两个模块,module.js和controller.js,模块我有:

export class Module {
    constructor(){
        const fetchParams = {
            method: "GET",
            mode: "cors",
            cache: "default"
        };
        const url = 'https://swapi.co/api/people/';
         fetch(url, fetchParams)
            .then(res => {
                if(!res.ok){
                    throw new Error(res.statusText);
                }
                return res.json();
            })
            .then(data => {
                const characters = data.results;
                this.characters = characters;
            })
    }
}
控制器中的

我:

import {Module} from "./module";
class Controller extends Module{
    constructor(){
        super();
    }

    checkData(){
           console.log(this.characters);
    }
}

在checkData()中我有未定义的,我怎样才能先从模块中等待答案,然后才能在checkData()中获取 PS:我正在使用webpack

1 个答案:

答案 0 :(得分:2)

Module中,将fetch调用移动到一个单独的方法,然后让子类调用该方法,这样它就可以将.then附加到promise并等待其完成(并处理错误) )。如果您有兴趣让代码看起来更清晰,look into using async/await syntax.

class Module {
  constructor() {
    this.characters = []
  }

  fetchCharacters() {
    const fetchParams = {
      method: "GET",
      mode: "cors",
      cache: "default",
    }

    const url = "https://swapi.co/api/people/"

    // IMPORTANT: return the promsie from fetch, so that callers can use it
    return fetch(url, fetchParams)
      .then(res => {
        if (!res.ok) {
          throw new Error(res.statusText)
        }
        return res.json()
      })
      .then(data => {
        const characters = data.results
        this.characters = characters
      })
  }
}

class Controller extends Module {
  checkData() {
    return this.fetchCharacters().then(() => {
      console.log(this.characters)
    })
  }
}

new Controller().checkData()