0
var app = express();
var cloud = firebase.firestore();

app.get('/getMyDatas', function (req, res) {
    let tList = [];
    let tJson = {};

    cloud.collection('contents/').orderBy('date').get().then((contents) => {

        contents.docs.forEach(cont=> {

            cloud.collection('userprofile/').where('userId', '==', cont.data().userId).get().then((users) => {
                users.docs.forEach(user => {
                    tJson = {description:cont.data().description, name:user.data().name};
                    tList.push(tJson);
                    tJson = {};
                    console.log("LIST IS FILLED SUCCESFULLY : " + JSON.stringify(tList));
                });  
            });   
        });
        console.log(" ??HERE THE LIST IS EMPTY : " + JSON.stringify(tList));
        res.json(tList);
    });

});
  • This code can create the list i want. But i can't use it on the line that says "res.json(tList)".

  • I can use on the line that says "console.log('My List : ' + JSON.stringify(tList));" (it shows my list correctly.)

  • res.json(tList) return "[]" empty list. How can i use this on this line?

  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Nick Sep 12 '20 at 23:40

1 Answers1

0

This code can create the list i want. But i can't use it on the line that says "res.json(tList)".

You aren't properly waiting for your asynchronous operations to be done before trying to use the result you're building in the asynchronous operations. So, you're trying to use tList before any of the items have been added to it (a timing problem).

You also don't have any proper error handling for any of your promises that might reject.

This is a much easier problem if you switch to a for loop where you can then use async/await to sequence your asynchronous operations:

app.get('/getMyDatas', async function (req, res) {
    try {
        let contents = await cloud.collection('contents/').orderBy('date').get();
        let tList = [];
        for (let cont of contents.docs) {
            let users = await cloud.collection('userprofile/').where('userId', '==', cont.data().userId).get();
            for (let user of users) {
                tList.push({description:cont.data().description, name:user.data().name});
            }
        }
        res.json(tList);
    } catch(e) {
        console.log(e);
        res.sendStatus(500);
    }
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979