Reputation: 519
supportChat: function(){
return functions.https.onRequest((req, res) => {
var userId = req.query.userId;
var object = {};
db.ref("/users/-KwZ2N38Q6a1a87p982/threads").orderByKey().once('value').then(function(snapshot) {
var snap = snapshot.val();
var keys = Object.keys(snap);
for (var i = 0; i < keys.length; i++){
k = keys[i];
db.ref("/threads/"+k+"/lastMessage").orderByKey().once('value').then(function(snapshot){
var snapshot = snapshot.val();
if (snapshot[i]["sender"] != "-KwZ2N38Q6a1a87p982"){
object[snap[i]["messageID"]] = snapshot;
}
});
}
console.log(object);
return res.status(200).send(object);
});
});
},
Each user in my database has a threads child, which shows all the chat threads they have going. Then we have another threads section of the database which has all the data of that thread.
What I'm trying to do is check a particular users' threads id's against the threads section of the database to find all the threads where the last message in the thread was not sent by me (current user).
I have no idea why I'm struggling with this. What is the right way to send all the snapshot.val() of each thread that meets my condition to the endpoint all in one push? Maybe my approach is way off.
Upvotes: 0
Views: 192
Reputation: 708206
To know when all the promises in your for
loop are done, you can accumulate the array of promises that you get from the loop and then use Promise.all()
to know when they are all done.
You also need to protect your for
loop index so that each invocation of the for
loop maintains its own index so it is still correct when your async .then()
handler is called. You can do that by switching your for
loop to use let i
instead of var i
.
supportChat: function(){
return functions.https.onRequest((req, res) => {
let userId = req.query.userId;
let object = {};
db.ref("/users/-KwZ2N38Q6a1a87p982/threads").orderByKey().once('value').then(function(snapshot) {
let snap = snapshot.val();
let keys = Object.keys(snap);
let promises = [];
for (let i = 0; i < keys.length; i++){
let k = keys[i];
promises.push(db.ref("/threads/"+k+"/lastMessage").orderByKey().once('value').then(function(snapshot){
let snapshot = snapshot.val();
if (snapshot[i]["sender"] != "-KwZ2N38Q6a1a87p982"){
object[snap[i]["messageID"]] = snapshot;
}
}));
}
return Promise.all(promises).then(() => {
console.log(object);
return res.send(object);
});
}).catch(err => {
console.log(err);
return res.sendStatus(500);
});
});
},
Other comments on the code:
FYI, if you're trying to actually return something from the supportChat()
function, please specify what that is. Right now, it is not clear what you expect to return from that function call.
And, you don't need the .status(200)
part of this:
res.status(200).send(object);
You can just do:
res.send(object);
all by itself and that will automatically use a status of 200.
And, you need a .catch()
handler to catch errors and send a response in the error condition.
Upvotes: 2