是否可以从react同时发出两个后端请求
下面的代码是第一个后端调用。post请求被发送到后端,然后我想做另一个请求。有可能吗?或者我必须等待后端响应,直到下一个请求发出?
我基本上想得到的是关于上传了多少文件的信息。上传可能需要3分钟,用户现在只看到一个加载图标。我想另外添加一个文本,如"50 of 800 Literatures uploaded"
和10秒后的"100 of 800 litereratures uploaded"
这基本上是我的代码:
class ProjectLiterature extends Component {
constructor(props) {
super(props);
this.state = {
isLoading:"false",
}
}
addLiterature(data, project_name) {
this.setState({ isLoading:true }, () => {
axios.post("http://127.0.0.1:5000/sendLiterature", data })
.then(res => {
this.setState({ isLoading: false })
})
})
}
如果两个请求互不依赖,则可以使用JavaScript的Promise.all()实现上述目的
如果第二个请求依赖于第一个请求的响应,则必须等待第一个请求完成,因为两个请求都必须按顺序执行
您可以看到axios docs为此,它们支持开箱即用的多个请求。 您也可以使用
Promise.all
而不是axios.all
,但如果其中一个请求失败,您将无法获得成功调用的响应。如果您希望在某些调用失败的情况下获得成功响应,则可以使用Promise.allSettled
相关问题 更多 >
编程相关推荐