Assigning query result to a variable

Hi All,

I need to assignthe result of a collection query to a variable. I have read a couple of posts and articles about the topic, but all of them either displays the result on the console or assigns the result to a site element.
On the basis of this article https://support.wix.com/en/article/velo-working-with-promises I tried these:

var carnr = queryCars ( “opel” );
var carnr2 = queryCars2 ( “opel” );

async function queryCars ( model ) {
const result = await wixData . query ( “cars” )
. eq ( “model” , model )
. count ();
console . log ( “in then 1” , result );
return result ;
}

function queryCars2 ( model ) {
return wixData . query ( “cars” )
. eq ( “model” , model )
. count ()
. then ( ( result ) => {
console . log ( “in then 2” , result );
return result
})
}

console . log ( “carnr” , carnr );
console . log ( “carnr2” , carnr2 );


carnr Promise<>
carnr2 Promise<>
in then 1 3
in then 2 3

I am quite confused, what am I doing wrong?

Thanks.
K.

For the first one queryCars() is also going to return a Promise since it is marked async. You can do the same await here: var carnr = await queryCars ( “opel” );

For the queryCars2() it’s essentially the same thing. Your .then() is a new Promise and it hasn’t resolved so you can do var carnr2 = await queryCars2(“opel”);

Promises/async can take a bit to really stick so just keep at it and one learning source I like for all things JS is MDN:

Thank you Anthony.
I’ve tried it, but I receive an error. :frowning:
‘Top-level ‘await’ expressions are only allowed when the ‘module’ option is set to ‘esnext’ or ‘system’, and the ‘target’ option is set to ‘es2017’ or higher.
Parsing error: Cannot use keyword ‘await’ outside an async function’

All you need is…

import wixData from 'wix-data';

//----------USER-INTERFACE---------------------------
let DATABASE = "CARS"; //<--- your DATABASE-ID here!!!
//----------USER-INTERFACE---------------------------

$w.onReady(async()=>{
    let myOpelCars = await getData("OPEL"); 
    let myBMWcars = await getData("BMW");
    let myVWcars = await getData("VW");

    console.log("OPEL-CARS: ", myOpelCars);
    console.log("BMW-CARS: ", myBMWcars);
    console.log("VW-CARS: ", myVWcars);
});

async function getData(model) {
    return wixData.query(DATABASE)
    .eq("model", model)
    .find()
    .then((res)=>{
        let items = res.items;
        return items
    })      
}

Modify the code and insert your own DB-ID (orange marked code-line).
Test it and see what you get inside of your → CONSOLE.

Example “CARS”-DATABASE…

Many thanks for your help.