49

I have an async method like below. It shows an error [ts] 'await' expression is only allowed within an async function. here await userProfile.set({. Can you tell me how to sort out it?

Note: Maybe it is due to I have tried to call promise inside the observable. Any clue?

 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()
        });
      }
    });
  }
Mark van Straten
  • 9,287
  • 3
  • 38
  • 57
Sampath
  • 63,341
  • 64
  • 307
  • 441

1 Answers1

80

Your main function is async but you’re using await in an arrow function which isn’t declared as async

userProfiles$.subscribe(async res => {
  if (res == null) {
    await userProfile.set({
...
Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
  • Yes, That is fixed. But am I doing right way here? calling `promise` inside the `observable/subscribe`? – Sampath Dec 08 '17 at 08:03
  • 1
    Above leads to another issue.Please see this: https://stackoverflow.com/questions/47710673/internal-assertion-failed-asyncqueue-is-already-failed – Sampath Dec 08 '17 at 08:55
  • Thanks for the help. Above issue maybe due to `firestore` issue. https://groups.google.com/forum/#!topic/google-cloud-firestore-discuss/hjng5VgktPM – Sampath Dec 08 '17 at 11:08