Ionic 4 等待异步方法 return

Ionic 4 wait for async method return

我有一个 Ionic 4 应用程序,我可以在其中使用 "cloud" service (http). 获取用户列表 cloud.getRemoteAccessUsers 是一个 asynchronous 方法,但我无法在服务中进行编辑。 我想创建一个检查用户是否存在的守卫,我将粘贴一个代码片段。

我想要 console.log(test) 显示一个数组,但只有 return 和 ZoneAwarePromise

canActivate(route: ActivatedRouteSnapshot): boolean {
    this.lock = this.cloud.getLocks().find(x => +x.Id === +route.paramMap.get('id'));

    let test = this.cloud.getRemoteAccessUsers(this.lock).then((data) => {
        return data;
    });

    console.log(test);

    return false;
}

您正在尝试 return Promise,但不是数据

如果您想在 CanActivate 方法内解析 Promise,请将您的 test 赋值移动到 then 内。

canActivate(route: ActivatedRouteSnapshot): boolean {
        this.lock = this.cloud.getLocks().find(x => +x.Id === +route.paramMap.get('id'));

        this.cloud.getRemoteAccessUsers(this.lock).then((data) => {
           let test = data;
           console.log(test);
        });

        return false;
 }

CanActivate界面也可以return一个Promise<boolean>或者Observable<boolean>

您可以 return 直接观察到:

canActivate(route: ActivatedRouteSnapshot): Promise<boolean> {
    this.lock = this.cloud.getLocks().find(x => +x.Id === +route.paramMap.get('id'));

    return this.cloud.getRemoteAccessUsers(this.lock).then((data) => {
        return data;
    });
}

如果data不是布尔值,你可以将callback中的逻辑写成return一个boolean.

您当前的测试日志将显示 ZoneAwarePromise 因为它是一个异步调用,所以您记录的是 promise 而不是 promise return 的值.

如果它是您想要的值,您可以在 .then

中记录 data
return test = this.cloud.getRemoteAccessUsers(this.lock).then((data) => {
    console.log(data)
    return data;
});

您也可以使用 async/await:

async canActivate(route: ActivatedRouteSnapshot): Promise<boolean> {
    this.lock = this.cloud.getLocks().find(x => +x.Id === +route.paramMap.get('id'));

    const test = await this.cloud.getRemoteAccessUsers(this.lock);
    console.log(test);
    return test;
}