React JS& Axios链接承诺 [英] React JS & Axios chaining promies

查看:77
本文介绍了React JS& Axios链接承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发react js应用程序,并且我们使用基于promise的库axios来调用API.

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 => {
    })

现在我可以使用

axios.all()

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.

如何以基于promise的方式而不是回调样式链接此调用?

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

推荐答案

对于这个Github问题,axios()axios.all()返回Promise对象,这些对象可以链接,但是您认为合适:

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

这篇关于React JS& Axios链接承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆