Taichi
Taichi

Reputation: 2587

How to handle successive axios.get in Promise?

I have data like this:

const resultData = {};
const data = {
  'foo': 'https://valid/url/1',
  'bar': 'https://valid/url/2',
  'baz': 'https://INVALID/url/3',
};

and I'd like to make a GET request to each urls.

If the request succeeds, I wanna add the response to resultData . If not, do nothing and do not raise any errors.

resultData will be like this:

resultData = {
  'foo': { ...responseOfFoo },
  'bar': { ...responseOfBar },
};

I wrote a code like below, but this does not realize what I want to do.

axios raise a error when the request fails with 404, and in addition, async/await does not seem to be working correctly.

import _ from 'lodash';

return new Promise((resolve, reject) => {
  const resultData = {};
  _.forEach(data, async (url, key) => {
    const res = await axios.get(url).catch(null);
    resultData[key] = res.data;
  });

  resolve(resultData);
});

What is wrong with this?

I also tried using axios.all or Promise.all, but could not handle each error of the request properly.

Upvotes: 1

Views: 1222

Answers (1)

Shilly
Shilly

Reputation: 8589

Use Promise.all and append the .catch() error handler to the end of each GET request, so that if they throw an error, it gets caught Before the Promise.all groups the results.

Something like:

const data = {
  'foo': 'https://valid/url/1',
  'bar': 'https://valid/url/2',
  'baz': 'https://INVALID/url/3',
};
Promise
.all(
    Object
    .entries( data )
    .map(({ name, url }) => axios
        .get( url )
        .catch( error => {
            throw new Error( `Failed GET request for ${ name }` );
            // Individual GET request error handler.
        })
    )
)
.then( results => {

})
.catch( error => {
    //  error on the Promise.all level, or whatever an individual error handler throws.
    //  So if the url of foo rejects, it will get thrown again by the catch clause after .get()
    //  So the error would be 'Failed GET request for foo'.
});

If you throw an error inside the catch clause of the GET requests, the error will bubble up to the catch clause after the Promise.all()

If you return a value from inside the catch clause, that will be the result of the get request then in the results array, so you can still use the two requests that did succeed.

The following example will just return an object describing the problem if one of the 'get requests' fails and will check the results together for validity.

Promise
.all([
  Promise.resolve( 'ok1' ).then( result => ({ "status": "ok", "value": result })),
  Promise.resolve( 'ok2' ).then( result => ({ "status": "ok", "value": result })),
  Promise.reject( 'nok3' ).catch( error => ({ "status": "nok", "value": error }))
])
.then( results => {
  results.forEach(( result, index ) => {
    if ( result.status === 'ok' ) console.log( `promise ${ index } resolved correctly: ${ result.value }`);
    else console.log( `promise ${ index } rejected with error: ${ result.value }` );
  });
})
.catch( error => console.error( error ));

If you need to be able to handle a GET request error individually and still trigger the .then() clause for the rest of the urls, you can't really batch all the requests together to begin with.

Upvotes: 2

Related Questions