axios并发请求:即使有些请求失败,任何方式从成功的请求中获取结果?

时间:2016-07-08 08:37:01

标签: javascript asynchronous request axios

我正在尝试查看如何使用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 )
})

2 个答案:

答案 0 :(得分:6)

为"可选"添加.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)
}))

答案 1 :(得分:0)

如果您希望保留来自成功请求的数据,即使其中一个(或多个)失败,您也可以使用 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 }
}))