0

I tried to use a aggregate function in my app and to catch the return values from this call. Everything is fine until I make a console.log(cases); inside the exec, but I fail to get the values back to a function as return value.

I use:

async function getListSuites() {

    const testdata =  await Suite.aggregate([
        {
            $sort: {
                identifier: 1,
                last: 1
            }
        },
        {
            $group: {
                _id: "$identifier",
                data: {
                    $last: {
                        last: "$last",
                        _id: "$_id"
                    }
                },
                count: {$sum: 1}
            }
        },
        //Optional
        {
            $project:{
                _id: "$data._id",
                date: "$data.last",
                name: "$_id",
                count: "$count"
            }
        }
    ]).exec((err, cases) => {
        if (err) throw err;
        console.log(cases); //works
        return  cases ;
    });

};

router.get('/jsonsuites', async function(req, res){


    var optionString = await getListSuites();

    console.log(optionString);

    res.send(optionString);
});

Any hint? Maybe a timing issue?

ingo
  • 776
  • 1
  • 10
  • 25

1 Answers1

2

You are defining an async function

async function getListSuites()

You are defining a constant within the function

const testdata =

You are returning nothing from the function.

So when you do

 var optionString = await getListSuites();

optionString will be undefined because nothing is returned from getListSuites()

add a return testdata at the end of your function.

async function bazbal() {
   return {yea:'baby'};
}
async function foobar() {
    const bar = await bazbal();
    return bar;
}
async function run() {

    var optionString = await foobar();
    console.log(optionString);
    var optionString = await foobar();
    console.log(optionString);
};

run();
Tschallacka
  • 27,901
  • 14
  • 88
  • 133
  • I think your answer is very clear but I also think that you did not recognised that the function use a callback t o return the values. The data from this callback I do not get really. – ingo Feb 24 '20 at 10:51
  • 1
    @ingo you don't return anything from the function. You don't pass a callback to the function that's called from within the function. Without you enabling the function to return something, nothing get's passed to your route handler. What you "return" in the exec is placed within the constant variable `testdata`. But `testdata` remains within the function and isn't passed "up the chain" by a return. The buck stops at putting the value in `testdata`. Just return testdata at the end of your function. – Tschallacka Feb 24 '20 at 10:52