繁体   English   中英

Javascript - 等待获取响应

[英]Javascript - await fetch response

我有一个 React-Native 应用程序,当组件安装时,我想通过调用我们服务 class 中的方法来获取数据,等待返回该数据,然后在 setState({}) 中设置该数据。 但是 setState({}) 在返回数据之前被调用。

//组件class

componentDidMount(){
   this.getData();
}

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

//服务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;

您必须返回axios.get调用。 否则async function将返回一个空的 promise(具有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 调用,它本身就是一个 promise 并且您无需等待它解析,因此无需使用async

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM