0

I am developing a react js application and we are using a promise based library axios for calling APIs.

Now, in the initial part of application, user gets a login page, when the login is successful, we contact different systems to retrieve some extra information about user.

axios
    .get('url to authentication endpoint') // 1st call
    .then(response => {
        // if login is successful
        // 1. retrieve the user preferences like, on the customised screens what fields user wanted to see
        axios.get('user preference endpoint') // 2nd call
        // 2. send a request to one more external systems, which calculates what user can see and not based on LDAP role
        axios.get('role calculation endpoint') // 3rd call
    })
    .catch(error => {
    })

Now I can see that I can use

axios.all()

for second and third call, but with promised based client, how to chain first and second call? To retrieve user preferences, I have to wait for user to be authenticated.

How to chain this calls in a promise based way, rather than callback style?

Priyank Thakkar
  • 4,752
  • 19
  • 57
  • 93

2 Answers2

2

as mentioned in the thread for this Github issue, axios() and axios.all() return Promise objects which can be chained however you see fit:

axios.get('/auth')
  .then(function(response) {
    return axios.all([ axios.get('/preferences'), axios.get('/roles') ]);
  })
  .then(function(responses) {
    const [
      preferencesResponse,
      rolesResponse
    ] = responses;
    // do more things
  })
  .catch(function(error) {
    console.log(error);
  });
Dan O
  • 6,022
  • 2
  • 32
  • 50
1

Dan O's answer is very good and it works perfectly but it's much readable using async/await although it's also working with promises under the hoood

async yourReactClassFunction(){
    try{
        let getAuth = await axios.get('/auth');

        //if login not successful return;

        let result = await Promise.all([axios.get('/preferences'), axios.get('/roles')]);

        //Do whatever with the results.

    }catch(e){
        //TODO error handling
    }
}

Although it's the same thing, 'feels' more readable in my very subjective opinion

forJ
  • 4,309
  • 6
  • 34
  • 60
  • in a real codebase I'd use `async/await` as well, since I think it's much easier to read too! But the original question uses `.then().catch()` syntax so I figured I'd do the same. – Dan O Apr 11 '18 at 14:19
  • @DanO yes that's exactly why I said your solution works perfectly! some people do prefer using promises so I thought I may offer another choice of solution – forJ Apr 12 '18 at 07:05