如何在多个异步请求中使用js async/await [英] How to use js async/await in mutiple async requests

查看:538
本文介绍了如何在多个异步请求中使用js async/await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 7,现在有一个方法(Angularguard CanActivate)包含一些嵌套的http调用方法,所有嵌套的http调用完成后,我需要返回数据.

I'm using Angular 7, now there is a method(Angular guard CanActivate) that contains some nested http call methods, i need to return data after all nested http call finished.

如下面的代码所示,仅在getCurrentUser()完成后,才在canActivate()中返回结果,而现在,由于getCurrentUser()尚未完成,它始终返回false.

As below code shows, only after getCurrentUser() finished, then return result in canActivate(), while now, it always return false because getCurrentUser() haven't finished.

export class AuthGuard implements  CanActivate{


  constructor(private commonService: CommonService) {
  }

  async canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    console.log('======');
    await this.getCurrentUser();
    return this.hasAccess;
  }

  hasAccess: boolean = false;

  async getCurrentUser(){
    await this.commonService.getToken().subscribe(token => {
      this.commonService.getCurrentUser(param, token).subscribe(o => {
        if(o.success){

          this.hasAccess = true;

        }else {
            window.location.href = '/forbidden.html';
          }
      }, error => {
        console.log(error);
      });
    });
    console.log("async");
  }
}

您可以看到有两种异步方法A,B应该等待,而A,B不是并行的,我检查了有关Promise和async/await的文档,没有找到解决方法.

you can see there are two async methods A,B should be await, and A,B are not parallel, i checked docs about Promise and async/await, didn't find solution.

由于应始终在异步之后等待,所有异步http调用完成后,我该怎么做才能让canActivate()返回结果?

As await should always follow async, how can i do to let canActivate() return result after all the async http call finished?

+++更新

this.commonService.getToken()this.commonService.getCurrentUser(param, token)是http调用(HttpClient),我尝试了很多解决方案,但没有结果.

this.commonService.getToken() and this.commonService.getCurrentUser(param, token) are http call(HttpClient), i tried a lot of solutions but no result.

推荐答案

参考上面的答案和其他人的帮助,我更新了代码,现在可以使用了. 我的更新是在 getToken() getUser()中使用new Promise(),而不是在await中使用,Promise具有该状态(待处理已解决已被拒绝),一旦状态更改,无论如何,只要Promise的状态更改为 reloved ,它就都不会更改,它不会被更改,Promise将返回它的值,否则,如果更改为 reject ,它将出错.

Refer to the above answers and other people's help, i updated my code and now it works. My update is use new Promise() in getToken(), getUser() instead await it, Promise has there status(pending,resolved,rejected), once status changed it won't be changed anyway, in that way, once Promise's status changed to resloved, it won't be changed and Promise will return it's value, else it will error if change to reject.

按如下所示附加我的更新代码:

Attach my updated code as below:

可以激活:

async canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    console.log('======');
    let token = await this.getToken();
    // let hasAccess = await this.getUser(token);
    return await this.getUser(token);
  }

getToken() getUser():

// return a Promise object and resolve(token)
getToken(){
    return new Promise((resolve, reject)=>{
      this.commonService.getToken().subscribe(token=>{
        resolve(token)
      })
    })
  }

  getUser(token: any) {
    return new Promise<boolean>((resolve, reject) => {
      this.commonService.getCurrentUser(param, token).subscribe(o => {
        if(o.success){

          hasAccess = true;
        }else {
          window.location.href = '/forbidden.html';
        }
        resolve(hasAccess);
      }, error => {
        console.log(error);
        resolve(hasAccess);
      });
    })
  }

我对 async/await Promise 不太熟悉,因此欢迎更正错误.

I'm not very familiar with async/await and Promise, so welcome correction error.

这篇关于如何在多个异步请求中使用js async/await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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