"await"表达式只允许在异步函数中使用

51

我有一个异步方法如下。它在这里 await userProfile.set({ 显示错误[ts] 'await' expression is only allowed within an async function.。你能告诉我该怎么解决吗?

注意:也许是因为我尝试在observable中调用promise造成的。有什么线索吗?

 async loginWithGoogle(): Promise<void> {
    const result = await this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
    const userId: string = result.uid;
    const userProfile: AngularFirestoreDocument<UserProfile> = this.fireStore.doc(`userProfile/${userId}`);
    const userProfiles: AngularFirestoreCollection<UserProfile> = this.fireStore.collection('userProfile/', ref => ref.where('email', '==', result.email));
    const userProfiles$: Observable<UserProfile[]> = userProfiles.valueChanges();
    userProfiles$.subscribe(res => {
      if (res == null) {
        await userProfile.set({ //here it shows error
          id: userId,
          email: result.email,
          creationTime: moment().format(),
          lastSignInTime: moment().format()
        });
      }
    });
  }
1个回答

82

你的主函数是异步的,但你在一个箭头函数中使用了 await ,而该函数并未声明为 async

userProfiles$.subscribe(async res => {
  if (res == null) {
    await userProfile.set({
...

是的,那个已经固定了。但是我在这里做的方式正确吗?在observable/subscribe中调用promise - Sampath
1
以上引出了另一个问题。请参考此链接:https://stackoverflow.com/questions/47710673/internal-assertion-failed-asyncqueue-is-already-failed - Sampath
感谢您的帮助。上述问题可能是由于firestore问题引起的。https://groups.google.com/forum/#!topic/google-cloud-firestore-discuss/hjng5VgktPM - Sampath

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接