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

11,305

Solution 1

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

Solution 2

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 }
}))
Share:
11,305
bstenm
Author by

bstenm

Updated on June 19, 2022

Comments

  • bstenm
    bstenm almost 2 years

    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 )
    })
    
  • Vikas Bansal
    Vikas Bansal over 5 years
    if a request is failing with 404 then its not coming into the then callback.. its going in catch. how to solve this?
  • Vikas Bansal
    Vikas Bansal over 5 years
    got the answer. just linking stackoverflow.com/questions/53064328/…