Array.push() not working inside forEach()

Hi, I am trying to fill up an array with a list of items pulled from a database. For some reason the array stays empty at the end.

I tried testing with console.log and can confirm that the data is coming through normally. It seems just the .push() is not working for some reason.

Any help is appreciated. Thanks,

$w.onReady(function () {
let temp= [];
    wixData.query("Products")
    .find()
    .then((result) => {
            result.items.forEach((item) => {
               //console.log(item["title"]);
                temp.push(item["title"]);
            });
     });
 //console.log(temp);
 });    
     

What do you see from the console.log() ? Do you have a field with the name title ?

When I do

console.log(item["title"]);

before the temp.push(), I can see the list of 15 product names that I have in the dataset e.g. :

AF Series
SF Series
RF Series

and so on.

Outside the loop I check if the temp array has been filled via :

console.log(temp);

but it shows empty. Somehow the data is coming through just fine, but I am unable to push the names of products in to an array via push.

Aha! I see the problem…

The console.log(temp) statement is not just outside the loop, but also outside of the query’s .then() . That’s because after calling wixData.query, the code continues right to the console.log() statement. The results are only returned later in the .then() function when the query has finished.

If you move the console.log() inside the .then(), you will see your newly created array:

$w.onReady(function () {
let temp= [];
    wixData.query("Products")
    .find()
    .then((result) => {
            result.items.forEach((item) => {
                //console.log(item["title]);   This works fine, I can see the list of 15 product names
                temp.push(item["title"]);
            });
            console.log(temp); // voila!            
     });
 //console.log(temp);  // here temp array is empty
 });

See these articles for an explanation of Promises and asynchronous code:

  • Corvid: Working with Promises

  • Promises, Promises

Haha, that’s amazing! It worked perfectly. I had no idea .then has a delayed execution. I’ll definitely read up more on this.

Thank you so much!