Home > Net >  Discord.js: Promise is resolving to undefined but console outputs correct value
Discord.js: Promise is resolving to undefined but console outputs correct value

Time:04-04

I am using mongoose to get an existing document containing a Number field called "eggs". I am able to get the document and print the number in the console. However, when assigning to a variable and pushing into an embed, it shows up as undefined.

client.on('messageCreate', message => { 
if(message.content.toLowerCase() === "~inv" && message.author.tag === "<discord tag>")
   sendInventory(message.author.id, message.author.tag, message.channelId);
...
}

async function sendInventory(id, authorTag ,msgChannelID){ 
   let eggPromise = await getData(id); 
   let numEggs = await Promise.resolve(eggPromise).then(function(value){return value;}); 
   let queryDesc = 'You haven't collected any eggs!';
   try{
      queryDesc = authorTag   ': '   'You have '   console.log(numEggs)  ' eggs!'
   }
   catch(err){}

   const embedLeaderboard = new MessageEmbed()
   .setColor('#624aa1')
   .setDescription(queryDesc);
   client.channels.cache.get(msgChannelID).send({embeds[embedLeaderboard]}).catch(console.error);
}

  function getData(id){
    User.findOne({discordId: id}, function(err, doc){
      if(err){console.log('query error');}
      else{
        console.log('eggs: ' doc.eggs);
        return doc.eggs;
      }
    });
  }

I've tried different methods for resolving the promise returned by getData() but I seem to be making a simple mistake. Any help is appreciated. Thank you!

CodePudding user response:

looks like you forgot to return the promise from the getData function, this should work:

function getData(id) {
  // User.findOne is a promise, you should return it
  return User.findOne({ discordId: id }).then(doc => doc.eggs); // using promises
}

Promises Mongoose: https://mongoosejs.com/docs/promises.html

CodePudding user response:

You need to await the .findOne

function getData(id){
await User.findOne({discordId: id}, function(err, doc){
  if(err){console.log('query error');}
  else{
    console.log('eggs: ' doc.eggs);
    return doc.eggs;
  }
});
}
  • Related