1

New to node and firebase authentication so please be nice.

I was making my website and was using firebase authentication. so when i was making a call to one of my apis, i wanted to get the users id token from firebase and send it to the back end where i can validate the token.

so below is an example of my code snippet, but anytime i call someFunction, it keeps on returning the function itself but i want to get the result of what that function computes. am i taking the wrong approach?

export const someFunction = async () => {
  return firebase.auth().onAuthStateChanged(async user => {
    if (user) {
      return user.getIdToken(true).then(async idToken => {
        let resp = await axios({
          headers: {
            authorization: idToken
          },
        })
        return {
          isSuccess: resp.data.isSuccess,
          message: resp.data.message
        }
      })
    } else {
      return {
        isSuccess: false,
        message: 'Could not validate user, please try again.'
      }
    }
  })
}

Solution

thanks to the comments and then getting me onto the right path i found How to Promisify this function - nodejs which led me to solve it by:

export const someFunction = async () => {
  // 1 - Create a new Promise
  return new Promise(function (resolve, reject) {
    // 2 - Copy-paste your code inside this function
    firebase.auth().onAuthStateChanged(user => {
      resolve(user)
    })
  })
}
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Attiq Ahmed
  • 105
  • 7
  • thanks, going off of that i noticed i have a observer not a callback or async or anything that is returned from calling someFunction above. will look around how to return that value but if any other hints im more then open :) – Attiq Ahmed Mar 13 '20 at 02:17
  • It *is* callback-based - see your `firebase.auth().onAuthStateChanged(async user => {`? Best idea would be to promisify the callback-based function, then return the Promise so it can be consumed with `.then` – CertainPerformance Mar 13 '20 at 02:18
  • thank you so much!!! alright i noticed what you were talking about, and figured it out – Attiq Ahmed Mar 13 '20 at 02:40

0 Answers0