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

问题描述 投票:0回答:3

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

但是,一个重要的部分是等待获取响应,但我不知道在哪里实现它。你会在API类的方法中实现异步等待吗?或者你会在React类中调用api_call方法实现async await吗?

React Class

实例化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

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;
  }
}
javascript reactjs ecmascript-6 async-await
3个回答
1
投票

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

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

然后等待该承诺解决:

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

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

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
   })
 }

然后你可以这样等待它:

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

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


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'的React类导入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'的React类导入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正确处理未解决的promise。

© www.soinside.com 2019 - 2024. All rights reserved.