【问题标题】:axios concurrent requests: any way to get the results from the successful requests even if some have failed?axios 并发请求:有什么方法可以从成功的请求中获取结果,即使有些请求失败了?
【发布时间】:2016-11-10 18:23:34
【问题描述】:

我正在尝试了解如何在 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 )
})

【问题讨论】:

标签: javascript asynchronous request axios


【解决方案1】:

为“可选”请求添加一个 .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)
}))

【讨论】:

【解决方案2】:

如果您想保留数据,即使其中一个(或多个)失败,您也可以使用 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 }
}))

【讨论】:

    猜你喜欢
    • 2019-04-03
    • 2019-02-25
    • 1970-01-01
    • 2018-04-19
    • 2020-11-26
    • 2020-03-29
    • 2015-08-18
    • 2021-12-29
    • 2020-07-08
    相关资源
    最近更新 更多