0

I'm having trouble with getting arrays to work as when I do a console.log statement after the function, I get an empty array... I know it has to do with the asynchronous nature of JS, but I can't figure out how to fix it. I tried using Promises but I still get an empty array in the console.log statement. Similarly, the total variable stays equal to 0 even though it should increment.

Any tips/suggestions? Thanks.

Here's my code:

let total = 0;
 let collections = [];
                    return Promise.all(courts.map(court => {
                      return new Promise((resolve, reject) => {
                        return Promise.all(court.users.map(async user => {
                          let tempPromise = new Promise((resolve, reject) => { 
                              setTimeout(() => {
                                  resolve();
                              }, 5000);
                          });
                                      return SignDetail.find({
                                        userName: user.userName,
                                        signStatus: "signIn",
                                      }).then(function(sign) { 
                                        if (user.userName.endsWith('zs')) { 
                                            let signCount = 0;
                                            if (sign.length > 1) {
                                                for (let j = 0; j < sign.length; j++) {
                                                    let courtObj = {courtName: sign[j].userName}; //make court object
                                                    signCount++; //increment each time there's a signature
                                                    if (j === sign.length - 1) { //only push object in array when all signatures have been counted
                                                        courtObj.signCount = signCount;
                                                        collections.push(courtObj);
                                                    } 
                                                }
                                            } 

                                        } //end here
                                      }); 
                          return tempPromise;
                        })).then(_ => resolve(collections));
                      })
                    })).then(collections => {
                      // HERE you will your collection and you can use this promise where this function is being called. 
                      console.log(collections);
                    });
    test() //call async function

    courts.forEach(court => { // count amount of signatures for only zs courts
        for (let i = 0; i < court.users.length; i++) {
              SignDetail.countDocuments({userName: court.users[i].userName}, 
            function(err, count) {
              if (count > 0) total = count;
                    });
                } 
              });

              console.log(total) // output should be greater than 0, but console outputs 0
              console.log(collections); //outputs []
  }
Edwin
  • 380
  • 1
  • 4
  • 18
  • You called `test`, but did not wait for it to resolve before iterating over `courts` again - you didn't give all the Promises time to resolve – CertainPerformance Mar 06 '19 at 05:42
  • Thanks for your quick reply. I thought Promise.all() resolves the promises? Should I use a .then() statement after? Sorry, I'm not very familiar with Promises yet. Thank you again! – Edwin Mar 06 '19 at 05:48
  • 1
    No, `Promise.all` just transforms an array of Promises into a single Promise (that resolves when all promises in the array are resolved) – CertainPerformance Mar 06 '19 at 05:49

0 Answers0