Struggling with Async/Await

Struggling with Async/Await
0.0 0

#1

Hi folks,
I am trying to implement an async/await function for the first time and I seem to be running into a road block. When I log the result of the following code I get “Promise { }” returned. According to the 15 youtube videos I’ve watched over the last hour, my async/await is structured correctly. Any advice would be much appreciated.

supportFunctions.getLeaders = async function(){
try{
const leaderList = await User.find({}).sort({“currentClue”: -1}).limit(5);
return leaderList;
}catch(err){
return err;
}
}


#2

You are going to need to supply the rest of your code.


#3

Hi randelldawson,
This function is running in a node/express app. This module contains only this function, here is the contents of the module:

//Module "SupportFunctions.js" ----------------------------------------
var mongoose = require("mongoose");
var User = require("../models/user");

var supportFunctions = {};

supportFunctions.getLeaders = async function(){
    try{
        const promiseList = await User.find({}).sort({"currentClue": -1}).limit(5).exec;
        return promistList;
    }catch(err){
        return err;
    }
}

module.exports = supportFunctions;

This function gets called in a controller when a user hits the home page.


#4

async / away in the end is a function generator that yelds Promises,

so yes, they return promises.
If you are (a)waiting for a promise.resolve, you’ll have that as a return value.

In this case i see you are using exec, so I’m wondering, are the db queries run as promises or it’s just a callback?
If so perhaps look at how your queries’s promises resolve :smile:

For the time being you can just then the query :slight_smile:

EDIT: I went on to mongoose built in promoses… guess what, exec resolve a promise… but you have to actually call the method:

await MyModel.findOne({}).exec()

and no
await MyModel.findOne({}).exec <— you’re not calling the promise :slight_smile:


#5

Thank you both for the help!