首页 > 解决方案 > Javascript - await fetch response

问题描述

I have a React-Native app and when the component mounts, I want to fetch data by calling a method in our services class, wait for that data to be returned, then set that data in setState({}). But setState({}) is called before the data is returned.

//Component class

componentDidMount(){
   this.getData();
}

async getData() {
    const data = await MyService.getData();
    this.setState({
        blah:data //undefined
    });
}

//Services Class

let MyService = {
    getData:function(){
        axios.get(url)

    .then(response => response.data)
    .then((data) => {
            //do stuff
          return data;//need to set this to state back in component class
     })
     .catch(error => {
            console.log(error);
     });   
      }
}

module.exports = MyService;

标签: javascript

解决方案


你必须回axios.get电话。否则async function将返回一个空的承诺(带有undefined值的承诺)。

let MyService = {
  getData: function() {
    return axios.get(url)
      .then(response => response.data)
      .then((data) => {
        // do stuff
        return data; // need to set this to state back in component class
      })
      .catch(error => {
        console.log(error);
      });   
  }
}

如果你返回这个 axios 调用,它本身就是一个承诺,你不会等到它解决,所以没有必要使用async.


推荐阅读