Bluebird.js 使用请求时出现未处理的拒绝错误

Bluebird.js Unhandled Rejection Error using request

我正在尝试调用 API 来获取一些数据。当调用returnsvalid数据时,有效!但是,当它遇到 API 错误,或者我想根据数据响应创建的错误时,我收到此错误:

Unhandled rejection Error: Data not found!
at Request.request.post [as _callback]
.
.

这些是我正在使用的文件:

let grabSomeData = new BluebirdPromise((resolve, reject) => {

  pullers.grabData(dataID, (err, res) => {

    if (err) {
      return reject(err);
    }

    return resolve(res);
  });


});

grabSomeData.then((fulfilled, rejected) => {
  console.log('res: ' + fulfilled);
  console.log('rej: ' + rejected);
});

在我发出 http 请求的其他文件中,

grabData(dataID, grabDataCallback)  {

  let bodyObj = {
    query: dataByIDQuery,
    variables: {
      id: dataID
    }
  };

  // grab the data
  request.post(
    {
      url: dataURL,
      body: JSON.stringify(bodyObj)
    }, (err, httpResponse, body) => {

        if (err) {
          return grabDataCallback(err);
        }

        let res = JSON.parse(body);

        if (res.data.dataByID !== null) {
          return grabDataCallback(null, res.data.dataByID);
        }

        return grabDataCallback(Boom.notFound('Data not found!'));
      }
  );

}

而不是这个:

grabSomeData.then((fulfilled, rejected) => {
  console.log('res: ' + fulfilled);
  console.log('rej: ' + rejected);
});

您需要使用:

grabSomeData.then((fulfilled) => {
  console.log('res: ' + fulfilled);
}, (rejected) => {
  console.log('rej: ' + rejected);
});

或者:

grabSomeData.then((fulfilled) => {
  console.log('res: ' + fulfilled);
}).catch((rejected) => {
  console.log('rej: ' + rejected);
});

有关未处理的拒绝警告(将来会是致命错误)的更多信息,请参阅此答案: