Reputation: 11
I'm trying Firebase and i Joined two tables and want node js express to send the response after the two query results are available
const database = firebase.database().ref();
const posts = database.child('posts');
const user = database.child('user');
let postWithName = [];
let postnames = []
function getUserNames(data) {
if (data) {
postnames = [] // NEW
Object.values(data).forEach((value) => {
user.child(value.user_id).once('value', sn => {
let content = value.content;
let date_posted = value.date_posted;
let id = value.id;
let title = value.title;
let user_id = value.user_id;
let user_Name = sn.val().name;
postnames.push({
"id": id,
"title": title,
"date_posted": date_posted,
"content": content,
"user_Name": user_Name,
"user_id": user_id
})
postWithName = postnames.sort(function (a, b) {
return b.id - a.id;
})
console.log(postnames)
})
})
}
}
function GetAll() {
posts.once('value', snap => {
postdata = snap.val()
getUserNames(postdata)
})
}
app.get('/getPosts', function (req, res) {
GetAll()
res.send({ "posts": postWithName })
})
the scheme is like this User Table example:
8721da2c-0028-430f-a995-0d03c8abb393:{
IsAdmin: 0,
Password: 123456,
email: '[email protected]',
id: 1,
image_file: 'https://i.imgur.com/fjYAIbl.png',
name: 'Abdelrahman',
phone: 1234567890,
public_id: '8721da2c-0028-430f-a995-0d03c8abb393'
}
Post Table example :
6:{
content: 'content 4',
date_posted: '2021-01-06 08:54:44',
id: 6,
title: 'test 4',
user_id: '8721da2c-0028-430f-a995-0d03c8abb393'
},
when using the provided code, i don't get data at first get request, but after it i get the data as needed, i just need the request to wait for firebase query to finish and the list to be populated then send the response, how can it be done ?
Upvotes: 1
Views: 311
Reputation: 123
i think you can simply make simple if condition inside the foreach so that when the length of the res array is equal to the data array you'll send the response
if (postWithName.length == data.length) {
res.send({ "posts": postWithName })
}
i hope i helped
Upvotes: 0
Reputation: 123
Not an ideal solution but you can use setTimeout function to delay the res.send for about two or three seconds until the queries are resolved. make this your last solution as it'd affect the performance
Upvotes: 0