jjzjj

javascript - axios 并发请求数 : any way to get the results from the successful requests even if some have failed?

coder 2025-03-14 原文

我正在尝试了解如何在 javascript 中处理并发异步请求,您是否知道使用 axios 获取成功请求结果的方法,即使请求失败了?如果不是,您将如何处理这种情况?

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 )
})

最佳答案

为“可选”请求添加一个 .catch block

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)
}))

关于javascript - axios 并发请求数 : any way to get the results from the successful requests even if some have failed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38262315/

有关javascript - axios 并发请求数 : any way to get the results from the successful requests even if some have failed?的更多相关文章

随机推荐