Reputation: 700
every time that I try to call data from real-time database returns null at first try but get right data at the second request
and that is my code
module.exports.getAllPosts = async () => {
await db.dbRef.child("posts").on('value', function (snap) {
temp = snap.val();
return;
});
return temp;
};
I am using async function everywhere and still doesn't work well I am using express to call this function
Upvotes: 0
Views: 156
Reputation: 598728
Data is loaded from Firebase asynchronously, like with many modern web APIs. This means that the main code continues to run, and your callback function is called after the data has been loaded.
You can best see this by adding some logging to your code:
console.log("Before attaching listener");
await db.dbRef.child("posts").on('value', function (snap) {
console.log("Got data");
});
console.log("After attaching listener");
When you run this code, you get:
Before attaching listener
After attaching listener
Got data
This is probably not the order you expected. But it completely explains why your code isn't working: by the time your return temp
runs, the data hasn't been loaded yet, and temp
is whatever it was before you started loading the data.
The solution is to not try and return the data immediately, but return a so-called promise of the data. Since you top-level function is already marked as async
this is a simple change:
module.exports.getAllPosts = async () => {
return await db.dbRef.child("posts").on('value', function (snap) {
return snap.val();
});
};
Upvotes: 1