Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 )
})
like image 848
bstenm Avatar asked Jul 08 '16 08:07

bstenm


2 Answers

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)
}))
like image 170
rajatbarman Avatar answered Oct 22 '22 11:10

rajatbarman


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 }
}))
like image 43
lu4ezar Avatar answered Oct 22 '22 11:10

lu4ezar