Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

javascript - 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
    }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...