Save query results in an array

Hi everyone! I’m developing a reviewing platform for students to review their teachers. I have a Database with all the reviews recived and now I want to filter ther reviews by teacher and show them in a dynamic page (for eachteacher). For that, I’m counting how many times people have voted some of the qualities and then I want to display the top 3.

I’m already being able to make the query and filter by teacher and quality. I’m trying to store the count in an array so then I can pick the 3 most voted. I managed to succesfully get the count (first console log), but when I try to save it in my array is not working (second console log). It displays [0, 0, 0, 0].

I’d appreciate any comment. Thanks!

export function dataset2_ready() {
    qualities();
}
function qualities() {
    let name = $w('#text1').text;    //Teacher name (dynamic page)
    let qualitiesArray = ['Fun', 'Inspirational', 'Relaxed', 'Concerned'];
    let qualitiesArrayCount = [0, 0, 0, 0];
    for (var i = 0; i < qualitiesArray.length; i++) {
        wixData.query("Reviews")
        .eq("reference", name)
        .eq("votedQualities", qualitiesArray[i])
        .find()
        .then( (results) => {
            let qualitiesCount = results.length;
            console.log(qualitiesCount);
            qualitiesArrayCount[i] = qualitiesCount;
            });
        }
    console.log(qualitiesArrayCount);        
}

Alonso,

To fetch the data from the server, takes some time. As constructed, the last console.log line executes before the first of the four queries is finished.

Here’s an article that describes the phenomena and how to work with it: https://support.wix.com/en/article/corvid-working-with-promises .

Using asynch await, each query in the for loop executes before moving onto the next one. See the end of the above-mentioned article.

export async function qualities() {
    let name = $w('#text1').text;    //Teacher name (dynamic page)
    let qualitiesArray = ['Fun', 'Inspirational', 'Relaxed', 'Concerned'];
    let qualitiesArrayCount = [0, 0, 0, 0];
    for (var i = 0; i < qualitiesArray.length; i++) {
        const results = await wixData.query("Reviews")
        .eq("reference",name)
        .eq("votedQualities", qualitiesArray[i])
        .find();
        let qualitiesCount = results.length;
        console.log(qualitiesCount);
        qualitiesArrayCount[i] = qualitiesCount;
    }
    console.log(qualitiesArrayCount);
}

Thank you for your comment, it worked perfectly!
I always thought code run line-by-line, now I’m courious to read about it so thanks for posting the article aswell.