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() }); } }); }
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.
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.
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 .
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.
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({ ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With