Here I’m creating an array that have property 1, then I’m trying to filter the results with only the highest number and then output it when calling the function, but it returns undefined. I’m trying to find to figure out what I’m doing wrong here. Thanks
function calcDifference() {
table.find({
"entries": 1
}) // select entries with "entries":1
.toArray(function(err, res_spr) { // create an array of found elements
let pop = res_spr.pop(); // delete last element of the array
let storeArraySpr = []; // new array to store property "number"
for (let i = 0; i < res_spr.length; i++) {
storeArraySpr.push(res_spr[i].number);
}
var resultSpr = Math.max(...storeArraySpr); // select highest entry
return resultSpr.toFixed(8); // meant to output the result when calling the function
});
}
console.log(calcDifference()); // returns undefined
2
Answers
You haven’t returned anything from that function.
You should add
return
beforetable.find
If
toArray
does not return values in that callback function. You can assign a value and return it.Note that this approach will work if
toArray
andfind
do not return promisesThe 3rd approach, if
find
andtoArray
are actually promisesIf
toArray
does not return results, you can assign variable again, but the difference is now we haveasync/await
Your main issue is that
calcDifference()
doesn’t have a return value. To solve this you first need to change the way you calltoArray()
. Like Barman pointed out in the comments:When you look at the documentation you’ll find that it does return a promise if you do not pass a callback function. Firstly we change
calcDifference
to anasync function
. Then weawait table.find({ "entries": 1 }).toArray()
instead of passing a callback. After that you can do your other stuff.Do note that an async function always returns a promise, so to use the return value you either have to
await
the value, or use athen()
construct if you are not in async context.