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
})
}
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.
‘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’