Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'await' expression is only allowed within an async function

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()         });       }     });   } 
like image 762
Sampath Avatar asked Dec 08 '17 07:12

Sampath


People also ask

Does await only works inside an async function?

The await operator is used to wait for a Promise . It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.

Can await be used without async?

You can not use the await keyword in a regular, non-async function. JavaScript engine will throw a syntax error if you try doing so. function caller() { // Using await in a non-async function.

What happens if you await a non async function?

This rule applies when the await operator is used on a non-Promise value. await operator pauses the execution of the current async function until the operand Promise is resolved. When the Promise is resolved, the execution is resumed and the resolved value is used as the result of the await .

Can you use await in a synchronous function?

Async/await helps you write synchronous-looking JavaScript code that works asynchronously. Await is in an async function to ensure that all promises that are returned in the function are synchronized. With async/await, there's no use of callbacks.


1 Answers

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({ ... 
like image 82
Sami Kuhmonen Avatar answered Sep 20 '22 22:09

Sami Kuhmonen