Camilo
Camilo

Reputation: 7204

Promise then() and catch() UnhandledPromiseRejectionWarning

I'm getting UnhandledPromiseRejectionWarning when I run this simple code:

var d = new Promise((resolve, reject) => {
  if (false) {
    resolve('hello world');
  } else {
    reject('no bueno');
  }
});

d.then((data) => console.log('success : ', data));

d.catch((error) => console.error('error : ', error));

The complete response is:

error :  no bueno
(node:12883) UnhandledPromiseRejectionWarning: no bueno
(node:12883) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:12883) [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. 

Seems like d.catch() is being fired. I noticed that if comment out d.then(), the warning message disappears.

I'm calling the script from the terminal like node foobar.js.

Am I doing something wrong?

Tested with node v8.14, v10 and v11 under MacOS High Sierra.

Upvotes: 1

Views: 350

Answers (1)

Felix Kling
Felix Kling

Reputation: 817010

d.then() creates a new promise that is rejected because d is rejected. That is the rejected promise that is not handled correctly.

You should chain .then and .catch instead:

d
  .then((data) => console.log('success : ', data))
  .catch((error) => console.error('error : ', error));

Upvotes: 4

Related Questions