Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return value read Firebase database

I am making a function in nodejs to read a value from the database in Firebase and return it. I read in the that way and get the right value by the console.log(), but when i made the return of the value doesn´t work properly when i call that function

function test() {

database.ref(sessionId + '/name/').once("value").then((snapshot) => {

    var name = snapshot.child("respuesta").val()
    console.log(name);
    return name;


});

}

If someone could help me. Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re not returning anything from test, so undefined is being implicitly returned. You can return the promise like this:

function test() {
  return database.ref(// everything else is identical
}

Note that this will be returning a promise that resolves to the name, not the name itself. It’s impossible to return the name, because that doesn’t exist yet. To interact with the eventual value of the promise, you can call .then on the promise:

test().then(name => {
  // Put your code that uses the name here
})

Or you can put your code in an async function and await the promise:

async function someFunction() {
  const name = await test();
  // Put your code that uses the name here
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading