bstenm
bstenm

Reputation: 139

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

Upvotes: 7

Views: 12311

Answers (2)

lu4ezar
lu4ezar

Reputation: 91

You can use Promise.allSettled when you want to keep data from successful requests even if one (or more) of them fails.

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

Upvotes: 3

rajatbarman
rajatbarman

Reputation: 149

Add a .catch block for the "optional" request

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

Upvotes: 11

Related Questions