How to handle rejection from a Promise

A clear rejection is always better than a fake promise, so when dealing with Promises in Node.JS consider the rejection aspect of the promise.

It is quite easy to handle, I prefer the Async method of handing promises, as it is much easier to read and understand.

Here is an example of how to throw a reject and handle the error:

function doSomething(message){
    return new Promise(function (fulfill, reject){
        setTimeout(() => {
          reject(message + " rejected");
        }, 2000);
    });
  }

(async function read() {
        try{
            const data = await doSomething('second promise');
            console.log(data);
        } catch (error) {
            console.log("error: " + error);
        }
    }
)();

console.log("Will hit here first, then wait for two seconds");

The response should look something like this:

Will hit here first, then wait for two seconds
error: second promise rejected

If you still wish to use the .then and .catch method of Promises then here syntax for that method:

doSomething('first promise')
    .then(data => {
        console.log(data);
    })
    .catch((err) => {
        console.log("error: " + err);
    });

For further reading take a look here