0

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: Console.logs

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?

  • 3
    Also, note that the [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) returns the the last operant, so `data,console.log('returned data:',data)` will return the return value of `console.log`, which is `undefined`. – Ivar Sep 28 '20 at 13:50
  • 3
    `getGuildData` doesn't `return` anything. A nested function within it has a `return` statement, but that's irrelevant to what `getGuildData` itself returns. – deceze Sep 28 '20 at 13:52
  • 1
    @Bee you cannot return the data because it doesn't exist yet. You can return a promise. `guildData.findId(id)` already creates a promise which will resolve to the data, so the last line of your function should be `return guildData.findById(id)` – Nicholas Tower Sep 28 '20 at 13:57
  • @NicholasTower I just put that in and ran it, still returns undefined. –  Sep 28 '20 at 14:01
  • Show us your updated code… – deceze Sep 28 '20 at 14:01
  • 2
    Yeah, no, same issue still. You just want `(id) => { const guildData = require(...); return guildData.findById(id); }`. Nothing more. – deceze Sep 28 '20 at 14:07

1 Answers1

0

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);
}
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98