paolov
paolov

Reputation: 2307

NodeJS returns Unhandled promise rejection error

My current code is:

const Discord = require('discord.js');
const client = new Discord.Client();

client.on('ready', () => {
  console.log('I am ready!');
});

function getData(location1) {
  var getResult = "";
  request.get('https://maps.googleapis.com/... '  + location1, (err, response) => {
  ...

  return getResult;
}

client.on('message', message => {
    if (message.content === 'ping') {
      message.channel.send('pong');
    }
    else if (message.content === 'query Melbourne') {
      message.channel.send( getData('Melbourne') ) ;
    }
} );

The first message.channel.send('pong') works fine. But the second message.channel.send keeps returning the result:

(node:16047) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): DiscordAPIError: Cannot send an empty message
(node:16047) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Just a novice at node so any guidance would be appreciated.

---- updated code below still errors in the same way:

  var PTest = function () {
      return new Promise(function (resolve, reject) {
          message.channel.send( getData('Melbourne') ) ;
      });
  }
  var myfunc = PTest();
  myfunc.then(function () {
       console.log("Promise Resolved");
  }).catch(function () {
       console.log("Promise Rejected");
  });

Upvotes: 0

Views: 9515

Answers (1)

Łukasz Szewczak
Łukasz Szewczak

Reputation: 1881

You just send an empty message just like the warning message writes (node:16047) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): DiscordAPIError: Cannot send an empty message

Function getData('Melbourne') in message.channel.send( getData('Melbourne') ) ; returns empty message and the Promise is rejected. Because you didn't handle Promise rejection, node.js writes warning on the console to inform you about this situation to prevent some potential abnormal situations which can happen thru ignoring handle Promise rejection.

To handle promise rejection please call .catch method for this send function

In your updated code, you create your own Promise

return new Promise(function (resolve, reject) {
      message.channel.send( getData('Melbourne') ) ;
  });

where Promise returned by message.channel.send method is still unhandled. you should write message.channel.send().catch(err => console.log(err));

Upvotes: 3

Related Questions