Javascript Beginner - Return Function

First time poster here. 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;
    }
    });
}

2 answers

  • answered 2018-01-11 20:47 Igor Paiva Ferreira

    In my folk words, you function should return trough "return" on the main scope, when the return is inside the query.., eq ... "then", the return is for wixData, not for the renderRating function

    function renderRating(applicantId) {    
    
        return 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;
            }
        });
    
    }
    

    Docs reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return

  • answered 2018-01-11 20:48 Niklas Higi

    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(() => { ... }).