【问题标题】:await with if statement and logical AND operator [closed]使用 if 语句和逻辑 AND 运算符等待 [关闭]
【发布时间】:2020-10-19 01:23:30
【问题描述】:
  onAngularFireAuthChanged(): void {
    this.afAuth.authState.subscribe(async (user: firebase.User) => {

      if (user && !(await this.afAuth.currentUser)) {  // here is the place
        // code
      }
    });
  }

我可以用&& 运算符编写上述await 吗?它似乎对我不起作用。有什么线索吗?

this.afAuth.currentUser:(property) currentUser: Promise<firebase.User>

【问题讨论】:

  • 为什么不对await this.afAuth.currentUser的结果使用变量?
  • @HereticMonkey 是的,我能做到。但如果我能像上面那样做,我想减少let/const
  • 你在这里混合了隐喻。你有subscribe,它用于rxjs,你有async/await,它是promise的域。将两者混合通常是一个坏主意(tm)。如果你想继续使用async/await,我认为你应该使用onAngularFireAuthChangedasync并使用const user = await this.afAuth.authState.toPromise();,或者在任何地方使用rxjs。
  • “它似乎对我不起作用”不是一个足够精确的错误描述来帮助你。 什么不起作用? 如何不起作用?你的代码有什么问题?您收到错误消息吗?错误信息是什么?你得到的结果不是你期望的结果吗?你期望什么结果,为什么,你得到的结果是什么,两者有什么不同?您正在观察的行为不是期望的行为吗?期望的行为是什么,为什么,观察到的行为是什么,它们有何不同? “好像”是什么意思?好不好用?

标签: javascript angular typescript ionic-framework async-await


【解决方案1】:

OP 的反馈

是的,你是对的。我的代码工作正常。但我的条件不正确。

原创

如有疑问,您始终可以通过将await 移出if 条件来简化代码:

onAngularFireAuthChanged(): void {
    this.afAuth.authState.subscribe(async (user: firebase.User) => {
      const currentUser = await this.afAuth.currentUser;
      if (user && !currentUser) {  // here is the place
        // code
      }
    });
  }

我怀疑这是问题所在,您发布的代码应该可以正常工作。其他地方可能有问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多