简体   繁体   English

axios 并发请求:有什么方法可以从成功的请求中获取结果,即使有些请求失败了?

[英]axios concurrent requests: any way to get the results from the successful requests even if some have failed?

I'm trying to see how to work with concurrent async requests in javascript, do you know a way with axios of getting the results of the successful requests even if one fails?我正在尝试查看如何在 javascript 中处理并发异步请求,您是否知道使用 axios 获取成功请求结果的方法,即使一个请求失败? If not, how would you handle that situation?如果不是,你会如何处理这种情况?

var axios = require( 'axios' )

var options = [{
      baseURL: 'https://some-base-url'
    , url: '/some-path&key=some-key'
    , method: 'post'
    , data: 'some-data'
}, {
      baseURL: 'https://some-base-url'
    , url: '/some-path&key=some-key'
    , method: 'post'
    , data: 'some-other-data'
}, {
      baseURL: 'https://some-base-url'
    , url: '/some-path&key=WRONG-KEY' // WRONG KEY
    , method: 'post'
    , data: 'some-other-data'
}]

axios.all([
      axios.request(options[ 0 ])
    , axios.request(options[ 1 ])
    , axios.request(options[ 2 ])
]).then(axios.spread(function (res1, res2, res3) {
    // when all requests successful
}))
.catch(function(res) {
    // third request was unsuccessful (403) but no way to get 
    // the results of the two previous successful ones?
    console.log( res )
})

Add a .catch block for the "optional" request为“可选”请求添加一个 .catch 块

axios.all([
      axios.request(options[ 0 ])
    , axios.request(options[ 1 ])
    , axios.request(options[ 2 ]).catch(function() { return false})
]).then(axios.spread(function (res1, res2, res3) {
    console.log(res1) //Respone of options[0]
    console.log(res2) //Response of options[1]
    console.log(res3) //False (When options[2] fails)
}))

You can use Promise.allSettled when you want to keep data from successful requests even if one (or more) of them fails.如果您希望保留来自成功请求的数据,即使其中一个(或多个)失败,您也可以使用Promise.allSettled

Promise.allSettled([
    axios.request(options[ 0 ]),
    axios.request(options[ 1 ]),
    axios.request(options[ 2 ]),
]).then(values => {
    console.log(values[0]) // { status: 'fulfilled', value: Respone of options[0]}
    console.log(values[1]) // { status: 'fulfilled', value: Respone of options[1]}
    console.log(values[2]) // { status: 'rejected', reason: Error: an error }
}))

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

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