Sebastian
Sebastian

Reputation: 47

async function don't return value in right order

I want to get user data from firestore, but functions don't behave as I want. When I run the init function I got a response in the console like: " in init", "after", "null", "user is active", but I want to receive a response like: "user is active", "in init", user data instead null," after";

I know it is probably simple, but I am sitting all day on this problem. What should I do to get data in this order?

init()

async function init () {
     await userIsActive()
    console.log("in init");     
  await getDaySpending();
    console.log("after") */
    
}

function userIsActive(){
    firebaseApp.auth().onAuthStateChanged( user=>{
    if(user){
      console.log("user is active");
      return true
    }else{
      console.log("no user");
      return false
    }
  })
  }

 function getDaySpending(period = '7-2020') {
    const user = firebase.auth().currentUser;
     console.log(user)    //I got null instead user data
    if(!user) return;      
    const uid = user.uid;
    const snap  = await  firebase.firestore().collection(uid).doc(period).get();
    if(snap.exists) {
      return snap.data().spending;
    } else {
      // handle the case where there was no data
    }
  }

Upvotes: 0

Views: 103

Answers (2)

Deadron
Deadron

Reputation: 5289

The issue is with the userIsActive function. You can't return a value from within an enclosed function.

// This function returns undefined
function asd() {
  (() => { return 1; })();
}

In this case, assuming you are using the firebase api correctly which I am not familiar with, you would need to use an explicit promise.

function userIsActive(){
  return new Promise((resolve, reject) => 
    firebaseApp.auth().onAuthStateChanged( user=>{
    if(user){
      console.log("user is active");
      return resolve(true)
    } else{
      console.log("no user");
      return resolve(false);
    }
 })
}

I suspect this is not the proper way to use this api though so hopefully someone more knowledgeable on the topic can chime in.

Upvotes: 2

Mindaugas Nakrosis
Mindaugas Nakrosis

Reputation: 138

init function is async if no await is present the execution is not paused and your code will then be executed in a non-blocking manner. Add keyword await.

Mozilla docs:

An async function can contain an await expression, that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

Upvotes: 0

Related Questions