Home > Software engineering >  Return value read Firebase database
Return value read Firebase database

Time:04-12

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

CodePudding user response:

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
}
  • Related