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 )
})
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)
}))
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 }
}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With