NodeJS returns 未处理的承诺拒绝错误

NodeJS returns Unhandled promise rejection error

我当前的代码是:

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') ) ;
    }
} );

第一个 message.channel.send('pong') 工作正常。但是第二个 message.channel.send 一直返回结果:

(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.

我只是 node 的新手,所以任何指导都将不胜感激。

---- 下面更新的代码仍然以同样的方式出错:

  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");
  });

你只是像警告消息写的那样发送一条空消息(node:16047) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): DiscordAPIError: Cannot send an empty message

函数 getData('Melbourne')message.channel.send( getData('Melbourne') ) ; returns 空消息中,Promise 被拒绝。因为你没有处理 Promise rejection,node.js 会在控制台上写警告来通知你这种情况,以防止一些潜在的异常情况,这些情况可能会通过忽略 handle Promise rejection 而发生。

要处理 promise 拒绝,请为此 send 函数调用 .catch 方法

在您更新的代码中,您创建了自己的 Promise

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

message.channel.send 方法返回的 Promise 仍未处理。你应该写 message.channel.send().catch(err => console.log(err));