Return result of query as variable

I am trying to get the result of this function and use it as number in calculation:

function GetAllSumVotes ( ) {

let SumAllVotes

wixData . aggregate ( “Competition” )
. sum ( “votes” )
. run ()
. then ( ( results ) => {
SumAllVotes = results . items [ 0 ]. votesSum ;
//console.log(“SumAllVotes:”,SumAllVotes)
})
return SumAllVotes ;
}

// running of the function
let z = GetAllSumVotes ();
console . log ( “SumAllVotes:” , z )

//result
SumAllVotes: undefined

How can i get the return of this function as number?

  1. Put the return SumAllVotes inside the then block.

  2. Add return before the wixData.query.

  3. When you call the function, use then like: GetAllSumVotes().then(z => console.log(“SumAllVotes:”,z));

Put the return SumAllVotes inside the then block.

[output: Parsing error: unexpected token return]

Post your code

function GetAllSumVotes ( ) {

let SumAllVotes
return
wixData . aggregate ( “Competition” )
. sum ( “votes” )
. run ()
. then ( ( results ) => {
SumAllVotes = results . items [ 0 ]. votesSum ;
//console.log(“SumAllVotes:”,SumAllVotes)
}

            **return**  SumAllVotes ; 

}

GetAllSumVotes (). then ( z => console . log ( “SumAllVotes:” , z ));

Get rid of the } before the final return and add }) after the final return line

Done, for this command:

GetAllSumVotes (). then ( z => console . log ( “SumAllVotes:” , z ));

the error is:
There was an error in your script
TypeError: Cannot read properties of undefined (reading ‘then’)

Post your full code again.

function GetAllSumVotes ( ) {

let SumAllVotes
return
wixData . aggregate ( “Competition” )
. sum ( “votes” )
. run ()
. then ( ( results ) => {
SumAllVotes = results . items [ 0 ]. votesSum ;
//console.log(“SumAllVotes:”,SumAllVotes)

            **return**  SumAllVotes ; 
            
            }) 

}

GetAllSumVotes (). then ( z => console . log ( “SumAllVotes:” , z ));

There are several issues that will cause you grief. First you need to check to ensure that the values you are summing are in fact summing valid data.

You should test to ensure that you got a valid sum returned. Second when you call the function, you need to wait for the result, because of the promise ( a promise that data will be returned at some point) being returned by the WixData.aggregate(). The await causes a pause in the code until the promise is fullfilled (the data is ready, summed etc. ) and the data results are returned. Then the code continues executing.

Remember the function where you call GetAllSumVotes(), must also have the async in front of it as well, since you are using the await, when calling GetAllSumVotes().

I have cleaned up your code and posted the changes/corrections below. Remember to use a .catch() with your .then(), when using WixData. This best practice will help you catch errors when querying data that might not be there. Also, always return a default value in your catch() as well. This way your website page won’t break when it hits the catch(). Often people will put in a catch, but not return anything. Unfortunately, your calling code often is expecting a value to be returned, and this is a way to avoid it from breaking. Often people using your website won’t be using a console and won’t see the error message from the catch(). This will silently allow your code to continue. You will of course have to deal with it in your calling code.

 
 export async function GetAllSumVotes() {

    return wixData.aggregate("Competition")
    .sum("votes")
    .run()
    .then( (results) => {
        if (results.items.length >0) {
            return results.items[0].votesSum;
        } else {
            return 0; // no records were found so return 0
        }
    })
    .catch ((error) => {
        console.log("[GetAllSumVotes()]::Error trying to read from Competition collection. Error was: "+error.message);
        return 0;
    })

}


// the function where this is put in must also have async added to the front of it
// since we're using the await
let sumVotes = await GetAllSumVotes()
console.log("SumAllVotes:",sumVotes);

Put the wixData.aggregate in the same line of the return and not in a new line. Like this:

return wixData.aggregate("Competition")

in this case you’re using the await out of the async function

Exactly, since I didn’t see your code where you actually call GetAllSumVotes (), there was no way for me to put async in the function declaration. That is why I put the comment above the await call.
I was just showing you how to setup your call to the GetAllSumVotes () function. It won’t run properly without the async. You will need to properly wrap it in a proper function call.

can you help me please?

As I said above. Your code was fine but you had to put the wixData right after the return and not in a new line .

thank you so much @J.D It works.
the result now is showing the right numbers:
input: GetAllSumVotes (). then ( z => console . log ( “SumAllVotes:” , z ));
output: SumAllVotes: 147

now how can i use the number only tom make addition and subtraction?
using this input doesn’t allow me to make mathematical operation on the number

any update?

Why not? You can do arithmetical operation.
For example:

GetAllSumVotes().then(z => z + 100 * 2 / 4 - 5));

@jonatandor35 there is something i don’t understand.

the result of this function is “z”.
i need to use the result in this function:
let PersonPercentage = parseFloat (( newVoteValue * 100 ) / z ). toFixed ( 2 ). concat ( “%” ) how can i make it?

@charbel-keedy


$w.onReady(() => {
  let newVoteValue  = 0.8;
  GetAllSumVotes().then(z => {
     let personPercentage = parseFloat((newVoteValue * 100) / z).toFixed(2).concat("%");
     $w('#personPercentageText).text = personPercentage;
  });
})