[英]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.