0

I am new to Node.js (usually develop in Java), but I am trying to create a REST service that retrieves data from firebase and then returns it as a JSON object.

I am not familiar with "promises", and after reading up on them, I think I understand the premise, but the implementation had been confusing me.

How can I tell my method to wait for the retrieving of data from my Firebase database?

Code:

getUsers(): String {

    var x;

    cooksRef.once('value').then(function(snapshot){
      x = JSON.stringify(snapshot.val())
      console.log("x is: " + x);
    }, function(error){
      console.log("error was: " + error)
    });

   console.log("Now x is: " + x);

   return x;
  }

Currently my code prints out:

Now x is: undefined
x is: {"R4DA34":{"age":31, "name": "example name"}}

I would like for it to wait and execute these statements sequentially, so that I can return the correct data to my controller"

x is: {"R4DA34":{"age":31, "name": "example name"}}
Now x is: {"R4DA34":{"age":31, "name": "example name"}}

2 Answers2

0

Try ES8 feature async/await that is supported in node.js 7.8 and above:

async function getUsers(): String {

const x = await cooksRef.once('value').then(function(snapshot){
  x = JSON.stringify(snapshot.val())
  console.log("x is: " + x);
  return x;
}, function(error){
  console.log("error was: " + error)
});

console.log("Now x is: " + x);

return x;
}
samuq
  • 306
  • 6
  • 16
0

If you don't want to use async/await, you need to have your code inside the then, like this:

getUsers(): String {

  var x;

  return cooksRef.once('value').then(function(snapshot){
    x = JSON.stringify(snapshot.val())
    console.log("x is: " + x);

    return x;
  }, function(error){
    console.log("error was: " + error)
  });
}

If you are ok with using async/await

async getUsers(): String {

  const snapshot = await cooksRef.once('value');
  const x = JSON.stringify(snapshot.val())
  return x

}

pd: I'm not sure if the syntax is correct for asyn in nestJs

iagowp
  • 2,428
  • 1
  • 21
  • 32