我正在尝试使我的代码变得简单,我想使用async并等待下面的代码 . 但是,我不知道如何暗示......有一些示例代码会很好 .
deletePost = (post) => {
var post_id = post;
try {
axios.delete(`http://localhost:4000/deleteAll/comments/${post_id}`)
.then(() => {
axios.delete(`http://localhost:4000/posts/${post_id}`);
}).then(() => {
axios.get('http://localhost:4000/posts')
.then(({data}) => {
this.setState({
posts: data.result
})
})
})
}
catch(err) {
console.error(err);
}
}
.
// This is what i understand so far.
deletePost = async(post) => {
var post_id = post;
try {
var deleteComments = await axios.delete(`http://localhost:4000/deleteAll/comments/${post_id}`);
var deletePost = await axios.delete(`http://localhost:4000/posts/${post_id}`);
var getPost = await axios.get('http://localhost:4000/posts'); // How can I change the state here??
// return ??
}
catch {
...
}
}
3 回答
你几乎就在那里 .
只有2条建议
由于您没有使用删除调用的响应,您可以删除它们
一旦你有更新的帖子设置状态像这样
完整代码
这是你想要做的(你不需要保存从2个第一个请求返回的
undefined
值,并且你的代码返回了承诺isn 't executed sequentially, the second promise isn' t,因此它不在链中):你甚至可以在代码的末尾写这样的方式:
你可以看到很多例子here,但是要在你的函数中实现async / await,请尝试使用以下代码: