2

I want to get a "value of Data" from Firebase Realtime Database. You can find my code below:

  async function getName() {
    const result = await firebase.database().ref('/users/' + user.user.uid)
    .once('value').
    then(async function(snapshot) {
      console.log("SNapshot =>");
      console.log(snapshot.val().displayName); // returns "John Doe"

      const result2 = await snapshot.val().displayName;

      return result2;
    });

    return result; // returns "Promise Object"
  };

It returns "Promise". But i want to get value not promise.

How should i fix my code?

Thanks.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
John Valdetine
  • 416
  • 2
  • 9
  • 26
  • 2
    `async` functions return a Promise by contract - it is the way they work. – Randy Casburn Mar 02 '19 at 22:40
  • You can't get a value from the future. Return the promise, have the user wait for the value. – Bergi Mar 02 '19 at 22:52
  • 1
    I only want to get a value of any data from my Firebase Realtime Database. It doesn't matter to use "async" function for me. How can i get value as `firebase.auth().currentUser.email`? – John Valdetine Mar 02 '19 at 23:05

2 Answers2

4

You are mixing up use of async/await with then()/catch(). You should pick one syntax or the other, not both together in this case. You are also trying to use await on something that is not a promise. Just write your function like this:

async function getName() {
  const snapshot = await firebase.database().ref('/users/' + user.user.uid).once('value')
  return snapshot.val().displayName
}

And call it like this:

const name = await getName()
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
1

The getname function is doing async operation so you can do:

try {
  await result = getName();
} catch (e) {
  throw e;
}

within an async function, or, if you prefer without async :

result.then((res) => console.log(res));
Dimitri Kopriwa
  • 13,139
  • 27
  • 98
  • 204