Search code examples
node.jsbluebirdhapi.js

Bluebird.js Unhandled Rejection Error using request


I am trying to make a call to an API to grab some data. When the call returns valid data, it works! However, when it hits a API error, or an error I want to create based off the data response, I get this error:

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

These are the files I am using:

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

In my other file making the http request,

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

}

Solution

  • Instead of this:

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

    You need to use:

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

    Or:

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

    For more info on the unhandled rejection warnings (that will be fatal errors in the future) see this answer: