I'm using firebase realtime database. I'm trying to get the data from the database and return it.
I need to return because I'm calling a function that should do this, get the data from the database and return. But in the function I'm calling this 'getData()' function, the value comes as 'undefined'.
Do I have to use asynchronous functions?? Or have another method. someone explain to me please
import { construct_bd } from "../../database.js";
function blog_posts() {
let section = document.getElementById("blog_posts_container");
function show() {
let data = construct_bd.getData("/posts");
console.log(data)
}
setTimeout(() => {
show()
}, 200);
...
}
database.js
...
// Variables
let database = firebase.database();
...
getData(reference){
let data;
database.ref(reference).once("value")
.then(snapshot => data = snapshot.val())
.catch(error => console.log(error))
.finally(() => {return data})
},
...
If the getData function returns a promise, then use await in your calling function. For example
async function show() {
let data = await construct_bd.getData("/posts");
console.log(data)
}
If getData is not a promise you can change it accordingly.
getData(reference){
return new Promise((resolve,reject) => {
database.ref(reference).once("value").
then(snapshot =>
data = snapshot.val();
resolve(data);
).catch(
error => reject(error)
).finally(() =>
reject(data);
)
});
}