Skip to content
Advertisement

JSON empty when is called from another file

I’m learning NodeJS and MongoDB. I dont know what is happening with this function.

getAllUsers = async () = {

let user;
let result = await new Connection().connect();
if (result.status == "ok")
    {
        user = await User.find();

    }
return user;
};

If I make a console.log before return user, it works fine (just print an JSON array with all info of the collection)

The problem is when I call it from another file (in my case, the router). If I do this, I receive an empty json.

Why is this happening?

Thanks for your help!!

Advertisement

Answer

When calling your function getAllUsers, you need to add await in front of it since it is an async function.

For example,

var listUsers = await getAllUsers();
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement