Q:

async await not waiting for resolve

So, im my nodeJS project I have this part of my code, that is not waiting for the await call
Controller.js
exports.getList = async function(request, response) {
try {
    const result = await useCase.getList()
    if (result == undefined) {
        utils.unavailable(response)
    }
    else if (result == null || result.length == 0) {
        utils.respond(response, 404, errCodes.NOT_FOUND)
    }
    else utils.respond(response, 200, result)
}
catch(e) {
    utils.unavailable(response)
}}

This is the function on the controller, it calls the response from the useCase
UseCase.js
exports.getList = async function() {
return await new Promise(function(resolve) {
    resolve(repository.getList())
})

Which also calls the repository
Repository.js
exports.getList = async function() {
MongoClient.connect(Constants.DB_URL, function(err, db) {
    if (err) {
        console.log(err)
        return undefined
    }  
    const dbo = db.db(Constants.DB_NAME)
    dbo.collection(Constants.DB_FEATURE1_COLLECTION).find({}).toArray(function(err, result) {
        if (err) {
            console.log(err)
            return undefined
        }
        db.close()
        return result
    })
});

So, what happens is that on the controller, the result is always undefined, since result hasn't been initialized, when it should have actually waited for the response of the Promise on the UseCase. So what am I doing wrong?

A:

getList function does not have return statement, and since it is async it returns a Promise that always resolves with undefined. I am not very familiar with MongoClient, but documentation says it returns a promise if no callback is specified. So you can change your code:
exports.getList = async function () {
    try {
        const db = await MongoClient.connect(Constants.DB_URL);
        const dbo = db.db(Constants.DB_NAME);
        const result = await dbo.collection(Constants.DB_FEATURE1_COLLECTION).find({}).toArray();
        db.close();
        return result
    } catch (err) {
        console.log(err);
        return undefined
    }
};

and UseCase.js:
exports.getList = function() { 
    return repository.getList(); // it returns a Promise there is no need to wrap it in async 
};

