React JS & Axios chaining promies

你离开我真会死。 提交于 2019-12-11 16:24:24

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/49742390/react-js-axios-chaining-promies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!