Javascript Axios异步等待响应
我正在尝试执行一些get和post请求,但不知怎的,状态更新得很晚(应该是.get,然后是.post) 状态已更新,但post在某种程度上出现了错误,即应该填充目标。我发现解决方法是使用异步等待。我试图实现它,但它不起作用 这是我试过的Javascript Axios异步等待响应,javascript,async-await,axios,Javascript,Async Await,Axios,我正在尝试执行一些get和post请求,但不知怎的,状态更新得很晚(应该是.get,然后是.post) 状态已更新,但post在某种程度上出现了错误,即应该填充目标。我发现解决方法是使用异步等待。我试图实现它,但它不起作用 这是我试过的 async componentDidMount() { const {destination, weight} = this.state; axios.get(`https://myapi`) .th
async componentDidMount() {
const {destination, weight} = this.state;
axios.get(`https://myapi`)
.then(res => {
const customer = res.data;
this.setState({ customer,
destination: customer[0].address[0].city,
}
})
const post = await axios.post(`https://api.cashless.vip/api/cost`, {destination, weight})
.then((post)=>{
console.log(this.state.destination);
const delivery = post.data;
this.setState({ delivery,
cost: delivery[0].cost[0].value
});
});
return post;
}
我试图用控制台记录目的地的状态,是的,它确实被更新了。我做的异步等待错误吗?谢谢你的帮助
try{
let res = await axios.get(`https://myapi`);
if (res) {
const customer = res.data;
this.setState({ customer,
destination: customer[0].address[0].city,
});
const postRes = await axios.post(`https://api.cashless.vip/api/cost`);
if (postRes) {
const delivery = post.data;
this.setState({ delivery,
cost: delivery[0].cost[0].value
});
}
}
}catch (err) {
console.log(err);
}
如果你想在外面使用post,那就由你决定。你有没有试过用Promise来做这件事?如果您使用的是
wait
,我不明白您为什么需要then
。等待
应该先打开然后
。为什么(res)?您应该向这个块中添加async,否则await将无法完成必须在函数定义中添加async的技巧,我认为这不是问题所在。关于if(res),get可能返回包含“”或null的空响应,因此在这种情况下不设置状态。当我将帖子放到if之外时,它工作正常。谢谢!!!!当我把帖子放在if外时,它工作得很好。谢谢!!!!
try{
let res = await axios.get(`https://myapi`);
if (res) {
const customer = res.data;
this.setState({ customer,
destination: customer[0].address[0].city,
});
const postRes = await axios.post(`https://api.cashless.vip/api/cost`);
if (postRes) {
const delivery = post.data;
this.setState({ delivery,
cost: delivery[0].cost[0].value
});
}
}
}catch (err) {
console.log(err);
}