Using variables outside queries.

Hello, I’m tring to use result variable outside quert results (to make a-b operation) but i cannot do it because variable is undefined. Can you help me please?

here the code:
export function calcolo()
{
let a;
let b;

  //Totali in lista 
  wixData.query("invitati_autorizzati") 
	.count() 
	.then( (results) => { 
                    a = results; 
} ); 

  //Totali iscritti 
  wixData.query("invitati_autorizzati") 
	.eq("iscritto", true) 
	.count() 
	.then( (results) => { 
            b=results; 
} ); 

console.log(a-b);
}

thanks
marco

Hi Marco,
Accessing data is an asynchronous operation, meaning you get the results at “a later time”.
That means that the order of execution of your code is something like:

  1. wixData.query(“invitati_autorizzati”).count()
  2. wixData.query(“invitati_autorizzati”).eq(“iscritto”, true).count()
  3. console.log(a-b)
  4. a = results;
  5. b=results;

Note that steps 4 and 5 can be switched, depending on the network status and how long the query runs on your database (5 can finish before 4), but the point here is that 4 and 5 will always happen after 3, because they are asynchronous.
What you need to do is “wait” for them to finish and only then print the result, something like this:

export function calcolo()
{
	//Totali in lista
	const firstPromise = wixData.query("invitati_autorizzati").count();

	//Totali iscritti
	const secondPromise = wixData.query("invitati_autorizzati")
		.eq("iscritto", true)
		.count();

	Promise.all([firstPromise, secondPromise])
		.then((a, b) => {
			console.log(a-b);
		});
}

Thanks a lot, it worked!
Marco