简体   繁体   English

关于使用 Axios 发送多个请求的查询 - React

[英]A query on sending multiple requests using Axios - React

There is a scenario where I need to call multiple services at once using Axios and I need to consider values for success API calls and neglect the failed API calls.有一种情况,我需要使用 Axios 一次调用多个服务,我需要考虑成功 API 调用的值并忽略失败的 API 调用。 For example, see the case below:例如,请看下面的案例:

let URL1 = "https://www.something.com"
let URL2 = "https://www.something1.com"
let URL3 = "https://www.something2.com"

const promise1 = axios.get(URL1);  // SUCCESS
const promise2 = axios.get(URL2);  // SAY THIS SERVICE CALL WAS FAILED SENDING 404 ERROR
const promise3 = axios.get(URL3);  // SUCCESS

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
}).catch((e)=>{ console.log("error",e)});

Say the Service 2 was failed while service 1 and 3 are succeeded, in such case the promise chain getting broken and throwing the error.假设服务 2 失败,而服务 1 和 3 成功,在这种情况下 promise 链被破坏并抛出错误。 I gonna need the output in such case as [response_1, null, response_3] .[response_1, null, response_3]这样的情况下,我需要 output。 Can you please guide me in how to achieve this?你能指导我如何实现这一目标吗? Thanks in advance.提前致谢。

My guess is that you should manually implement it by returning Promise.resolve() on catch .我的猜测是您应该通过在catch上返回Promise.resolve()手动实现它

let URL1 = "https://www.something.com"
let URL2 = "https://www.something1.com"
let URL3 = "https://www.something2.com"

const promise1 = axios.get(URL1).catch(() => Promise.resolve());  // SUCCESS
const promise2 = axios.get(URL2).catch(() => Promise.resolve());  // SAY THIS SERVICE CALL WAS FAILED SENDING 404 ERROR
const promise3 = axios.get(URL3).catch(() => Promise.resolve());  // SUCCESS

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
}).catch((e)=>{ console.log("error",e)});

This way, if an axios request fail, it will first get in axios.catch then return a success with whatever value you need.这样,如果 axios 请求失败,它将首先进入 axios.catch然后返回成功,并返回您需要的任何值。

You can find more informations about Promise chaining on MDN Using Promises Chaining ( like chaining after a catch ).您可以在MDN 上使用 Promises 链接找到有关Promise 链接的更多信息(例如在 catch 之后链接)。

Promise.all() will not see any catch, so keep in mind those request will no longer be able to fail on Promise.all . Promise.all()将看不到任何捕获,因此请记住,这些请求将不再能够Promise.all上失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM