'await' expression is only allowed within an async function

Sampath picture Sampath · Dec 8, 2017 · Viewed 23.5k times · Source

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()
        });
      }
    });
  }

Answer

Sami Kuhmonen picture Sami Kuhmonen · Dec 8, 2017

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({
...