I'm trying to make a function where I can easily call my MongoDB.
This is the function code/hanlder:
let get = {};
get.getGuildData = (id) => {
const guildData = require('./models/guilds.js')
guildData.findById(id).then(async (data) => {
return guildData.findById(id)
})
};
module.exports = { get }
This is where I am calling the function:
const getGuild = bee.get.getGuildData(msg.guildID)
console.log(getGuild)
It returns undefined, but the console.log on the actual function returns the correct thing:
Let me know if anyone knows a solution to this.
I can not find an answer in this post. How do I return the response from an asynchronous call?
You cannot return the data, because it doesn't exist yet. What you can do is return a promise. guildData.findById(id)
apparently is already returning a promise which resolves to the data, so you do not need to call .then
on it to create a new promise.
get.getGuildData = (id) => {
const guildData = require('./models/guilds.js')
return guildData.findById(id);
};
Since the function is now returning a promise, any code that calls it will need to work with promises. Either call .then
on the promise:
bee.get.getGuildData(msg.guildID)
.then(data => {
console.log(data);
});
Or if you're in an async function, use await:
async function someFunction() {
const data = await bee.get.getGuildData(msg.guildID);
console.log(data);
}