简体   繁体   中英

I get "undefined" when I use return;

I get a snapshot value that if I console.log it works but I when I return the value I get "undefined".

I tried changing variable and changing the return values and using await and async .

async function GetElements(element, place) {
firebase.database().ref().child(place).orderByChild("uid").equalTo(element).once('value', (snapshot) => {
    snapshot.forEach(function(childSnapshot) {
      Holder = childSnapshot.val();
    });
  }, (errorObject) => {
    console.log("User does not exist");
    document.cookie = "uid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT";
    window.location.replace("login.html");
  });
  return Holder;
}
async function Test() {
  var bob = await GetElements("POkHi19eyZTfdeYECVpZByeVv2R2", "users/");
  console.log(bob)
}
Test()

You could try this:

async function GetElements(element,place) {
  firebase.database().ref().child(place).orderByChild("uid").equalTo(element).once('value', (snapshot) => {

    snapshot.forEach(function(childSnapshot) {
            
      Holder = childSnapshot.val();
      
    });

    return Holder;
  }, (errorObject) => {
    console.log("User does not exist");
    document.cookie = "uid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT";
    window.location.replace("login.html");
  });
}

This way, the return statement will only be executed after the callback function has been called and "Holder" has been set to the correct value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM