Hi,
I'm pretty new to coding and having a hard time understanding async/await.
My question: why is createUserInFirestore
executing before userExists
?
async googleLogin () {
var provider = new firebase.auth.GoogleAuthProvider()
try {
const result = await firebase.auth().signInWithPopup(provider)
const uid = result.user.uid
const userExists = await this.userExists(uid)
if (!userExists) {
this.createUserInFirestore(uid)
}
} catch (error) {...}
async userExists (uid) {
const usersRef = db.collection('users').doc(uid)
usersRef.get()
.then(async (docSnapshot) => {
if (docSnapshot.exists) {
console.log('user already exists in firestore')
return true
} else {
console.log('no user in firestore')
return false
}
})
}
Thanks
Top comments (3)
Hey, do you have a working copy like a codepen or codesandbox where the error can be reproduced? Also, there is no need for the then callback to be async here
Mozilla has very good documentation. I always consult it.
developer.mozilla.org/en-US/docs/W...
A function marked as async will happen concurrently with other code. So for example, here's some very slightly altered code from the MDN documentation:
If you run that, what you'll see output is:
and a couple seconds later
The MDN documentation explains that only async functions are allowed to use the "await" keyword. This causes the function's execution to pause and wait for some Promise to be fulfilled. This isn't allowed in normal functions because it would 'lock up' the execution of javascript code.
My suggestion is that you go to Mozilla developer network and inside the JavaScript documentation you search for everything related to Promises. Async/await is just syntactic sugar wrapping around a Promise. I apologize if this doesn't answer your question in full.
PS: userExists is executing before the other one because even if the two of them look "ordered" in code when they are placed inside the event loop the one that finishes first will be "fulfilled" and thus return before the other