Problems getting data from Firebase Realtime Database

Asked

Viewed 52 times

0

I’m learning to use Firebase and this is my first project, but when I try to put the values of the database in a variable it returns Promise { <pending> }, the code in question is:

const firebase = require('firebase-admin');
const key = require('./teste-a43e2-firebase-adminsdk-3sd3256d0-adc6b.json');

firebase.initializeApp({
  credential: firebase.credential.cert(key),
  databaseURL: "https://teste-a43e2.firebaseio.com"
});

const data = firebase.database().ref('/date').once('value').then(snapshot => {
  let database = (snapshot.val()) || 'Anonymous';
  console.log(database);
  return database
});

console.log(data);

as the first console.log shows the function is returning the values of the database, but the datais receiving a precedent and not the values

inserir a descrição da imagem aqui

  • 1

    This is due to the asynchronous nature of Javascript. You cannot simply remove an "inside" value from an Promise because it is not possible to determine when the value will be available. I explain a little better about how to deal with this in this other question: How to assign a Promise result to a variable?. But in short, you should simply handle the data solved from within the callback of then. You can chain multiple promises or use the async/await to better organize the code if necessary.

  • This answers your question? How to assign a Promise result to a variable?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.