Bluebird.js未处理拒绝错误使用请求

我正在尝试调用API来获取一些数据。 当通话返回有效的数据,它的工作原理! 但是,当它遇到一个API错误,或者我想创build基于数据响应的错误,我得到这个错误:

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

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

  • 我是否应该避免asynchronous处理Promise拒绝?