ReactJS:如何同时发出两个后端请求?

2024-10-03 23:23:22 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以从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 })
        })
    })
  }

Tags: 文件of代码用户信息falsedataprops
2条回答

如果两个请求互不依赖,则可以使用JavaScript的Promise.all()实现上述目的

const request1 = axios.get('http://127.0.0.1:5000/sendLiterature');
const request2 = axios.get(url2);

Promise.all([request1,request2]).then([res1, res2] => {
  // handle the rest
}).catch((error) =>  {
  console.error(error);
  // carry out error handling
});

如果第二个请求依赖于第一个请求的响应,则必须等待第一个请求完成,因为两个请求都必须按顺序执行

const res = await axios.get('http://127.0.0.1:5000/sendLiterature');
// carry out the rest

您可以看到axios docs为此,它们支持开箱即用的多个请求。 您也可以使用Promise.all而不是axios.all,但如果其中一个请求失败,您将无法获得成功调用的响应。如果您希望在某些调用失败的情况下获得成功响应,则可以使用Promise.allSettled

相关问题 更多 >