DEV Community

Joachim Waldmann
Joachim Waldmann

Posted on

I just don't understand async/await 😒!

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)

Collapse
 
manan30 profile image
Manan Joshi

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

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
          }
        })
Collapse
 
paxfeline profile image
David Newberry • Edited

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:


function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();

console.log( "after async call" );

If you run that, what you'll see output is:

calling
after async call

and a couple seconds later

resolved

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.

Collapse
 
inigogb profile image
BaronVonHex • Edited

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