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 data
is receiving a precedent and not the values
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 theasync/await
to better organize the code if necessary.– Luiz Felipe
This answers your question? How to assign a Promise result to a variable?
– novic