2

I have basic Javascript knowledge and a question on return functions. I've read as many posts as I can find, but still unable to solve a problem I am having. The following code calculates the average rating from users in a database I have. The code works, but it is not "returning" the rating. It calculates it properly. How should the syntax of this be structured so it returns the rating I calculated?

function renderRating(applicantId) {    

wixData.query("Project_Applications")
    .eq('_owner', applicantId)
    .eq('orgCompleted', "Yes")
    .find()
    .then(res => {
        if (res.length > 0) {
            let reviews = res.items;
            let stats = reviews.reduce((agg, item) => {                     
                return {
                sum: agg.sum+item.userRating, 
                count: agg.count+1
                };
                }, {sum: 0, count: 0});

        let rating = (Math.round(stats.sum * 2 / stats.count) / 2);     
        return rating;
    }
    });
}
anothermh
  • 9,815
  • 3
  • 33
  • 52
David Seroy
  • 179
  • 1
  • 14

1 Answers1

2

The function you wrote does something asynchronous: it queries data from a database using a Promise-based API meaning that the return-ed value isn't "ready" immediately. Simply return the Promise and you're done.

function renderRating(applicantId) {
  return wixData.query("Project_Applications") // ...
}

Now your function returns a Promise as well meaning that when you want to use it somewhere you have to use .then(() => { ... }).

Niklas Higi
  • 2,188
  • 1
  • 14
  • 30