调用导入类的方法时使用Async / Await

时间:2018-09-06 18:34:22

标签: javascript reactjs ecmascript-6 async-await

使用React和API调用,我将API提取分离到另一个类。目标是在此之后创建API类的实例以调用“ api_call()” 然后将数据存储在实例对象中,然后我将获取该数据并根据实际数据更改反应状态。

但是,重要的部分是等待提取响应,但是我不确定在哪里实现它。您会在API类的方法内实现异步等待吗?还是在React类中调用api_call方法的地方实现异步等待?

反应班

实例化了API obj,并调用了获取过程

class App extends Component {
  constructor(props){
    super(props);

    this.state = {
    }
  }

  componentDidMount(){
    var RESTAPI = new API();
    RESTAPI.api_call();
    console.log(RESTAPI.infomation);
  }
 }

API类

class API {
  constructor(){
    this.url = "https://restcountries.eu/rest/v2/all";
    this.data = null;
    this.information = null;
  }

  api_call(){    
    fetch(this.url)
    .then((response) => response.json())
    .then(function(data){
      this.data = data;
      this.api_sort();
    }.bind(this))
  }

  api_sort(){    
    var infoObj = {
      name: this.data[0].name
    }

    this.information = infoObj;
  }
}

3 个答案:

答案 0 :(得分:1)

api_call已经在创建一个诺言,只是让它返回那个诺言

def lookup(self, var=var):
    var = var

然后等待该诺言解决:

api_call(){    
  return fetch(this.url) // <--- added return statement
   .then((response) => response.json())
   .then(function(data){
     this.data = data;
     this.api_sort();
   }.bind(this))
 }

此外,您应该考虑使Promise使用相关数据进行解析,而不是解析为undefined。

async componentDidMount(){
  const RESTAPI = new API();
  await RESTAPI.api_call();
  console.log(RESTAPI.infomation);
}

然后您可以像这样等待它:

api_call(){    
  return fetch(this.url)
   .then((response) => response.json())
   .then((data) => { // <-- changed to arrow function, so there's no need to bind
     this.data = data;
     this.api_sort();
     return this.information; // <--- added return statement
   })
 }

答案 1 :(得分:0)

起初,我不会为API使用类,因为它实际上没有实例,所以可能是:

 function getData(url) {
   let response;
   return function() {
     if(response) return response;
     return response = fetch(url)
        .then(res => res.json())
        .then(res => res.data);
   };
}

 const API = {
  all: getData("https://restcountries.eu/rest/v2/all"),
  //...
 }

然后在组件内部,您可以等待响应:

 async componentDidMount() {
   const { 0: {name} } = await API.all();
   this.setState({ name });
 }

然后,您可以在组件内部使用name

答案 2 :(得分:0)

这是一种简单的方法,可以使用常量和函数作为这些常量的属性,而无需创建类。这会将函数设置为实用程序处理程序的属性,如果要向api添加更多函数,这将很有用。

调用API并进行排序

API类

const values = {
    url: "https://restcountries.eu/rest/v2/all"
};

const api = {
    call: async function(url = null){    
        try{
            if(url === null){
                url = values.url;
            }

            let response = await fetch(url, options);
            let responseOK = response && response.ok;
            if (responseOK) {
                let data = await response.json();
                return api.sort(data);
            } else {
                // handle response not ok
            }
        } catch(e){
            // handle promise errors
        }
    },

    sort: function(data){
        // return sorted data
    }
}

export default api;

反应班     从'api.js'导入api;

class App extends Component {
    constructor(props){
        super(props);

        this.state = {
        }
    }

    async componentDidMount() {
        let result = await api.call(); // or api.call(someUrl)
        // do something with result
    }
}

仅在需要时在API调用后排序

使用此解决方案,您还可以将api调用与数据排序分开,如下所示:

API类

const values = {
    url: "https://restcountries.eu/rest/v2/all"
};

const api = {
    call: async function(url = null){    
        try{
            if(url === null){
                url = values.url;
            }

            let response = await fetch(url, options);
            let responseOK = response && response.ok;
            if (responseOK) {
                return await response.json();
            } else {
                // handle response not ok
            }
        } catch(e){
            // handle promise errors
        }
    },

    sort: function(data){
        // return sorted data
    }
}

export default api;

反应班     从'api.js'导入api;

class App extends Component {
    constructor(props){
        super(props);

        this.state = {
            sort: true,
        }
    }

    async componentDidMount() {
        let result = await api.call(); // or api.call(someUrl)
        // do something with result
        // sort if necessary
        let sortedResult = api.sort(result);
        // do something with sortedResult
    }
}

您也可以使用Axios,如this answer所示。

如果使用这种方式,请记住使用 try / catch 正确处理未解决的承诺。