Home > database >  Firebase asyc/await not returning complete result from foreach loop
Firebase asyc/await not returning complete result from foreach loop

Time:10-23

I am struggling to get this working properly. I have this function in my nodejs backend

let data = [];
let lists = [];
var userId = request.params.userId;
var coll = db.collection("forms");
var query = coll.where("formUser", "==", userId);
await query.get().then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
        var forms = doc.data();
        var listIDs = doc.data().formLists;

        listIDs.forEach(listId => {
            db.collection("lists").where("listId", "==", listId).get().then(function (snapshot) {
                snapshot.forEach(function (d) {
                    lists.push({ "id": d.data().listId, "text": d.data().listName });
                });
            });
        });
        forms.formLists = lists;
        data.push(forms);
    });
});

The second loop for some reason isn't just working, the result of data is from the first loop and if I put the same function inside my javascript frontend, I get the complete data with the listIDs result.

Any ideas please?

CodePudding user response:

Adding a single await does not suddenly make all the code under it run synchronously. It's also typically an antipattern to combine await and then as you're doing. I recommend staying away from async / await until you've mastered asynchronous behavior, and sticking to then and explicitly dealing with the promises until then.

If the code you shared run in Cloud Functions, you'll need to return a single promise that resolves once all asynchronous (read and write) operations complete. Since you have a lot of such operations, you'll want to capture all the promises you get from them into an array, and then use Promise.all() for the return value:

var userId = request.params.userId;
var coll = db.collection("forms");
var query = coll.where("formUser", "==", userId);
return query.get().then(function (querySnapshot) { //            
  • Related