I want fetch all child nodes in a given path from Firebase Realtime Database and which I get using a similar method to this.
But my main issue is I want to merge then into a single string and I tried out something like this:
if(userInput === '/showUsers') {
const usersRef = `Data/users/`
let returnText = `Your users:`
admin.database().ref(usersRef).on("value", function (snapshot) {
snapshot.forEach(function (e) {
const xSnap = e.val()
const xName = xSnap.Name
const xId = xSnap.id
console.log(`${xName} - ${xId}`)
returnText.concat(`n${xName}n${xId}`)
console.log(returnText)
})
})
return res.status(200).send({
method: 'sendMessage',
chat_id,
reply_to_message_id: messageIdtoReply,
text: `${returnText}`,
parse_mode: 'HTML'
})
}
So all the child nodes are getting fetched and they get logged into the console but the returnText
always remain to it’s predefined value. I have to do this because I want to return the data into a Telegram bot so it must be a single string as I cannot return multiple values to telegram bot.
I don’t want to use a for-loop
because those nodes won’t be named as 1,2,3 or so on that I can use a loop.
Also how do I fetch only first 10 users/records a time so that it won’t overflow Telegram message limit?
Expected Output:
All I want is to get the data into a single message.
2
Answers
I am not very familiar with typescript to be honest but I will try to answer your question.
Getting values from firebase is
asynchronous
which meansIf you access
returnText
variable online 15
for example it might be executed before the above function.I think you should put this in a function with a call back that gets you returnText when everything finishes executing.
For Example:
Here we have function
concatResults
with a parametercb
callback which is called when the foreach finishes it’s job.How to use?
Simply:
Here we have implemented our callback that will be called after
concatResults
function finishes it’s job.In JavaScript, the
.concat()
function does not alter the value of any string. It just returns the concatenated values (w3 reference). Thus, you should use it as follows:Also, due to the single threaded nature of JS, in order to return the concatenated text you should perform the return inside the
admin.database().ref(usersRef).on("value", function (snapshot) { ... }
block or better yet, use a Promise as explained here