Possible unhandled promise rejection

A promise rejection occurs when a promise is rejected, but there is no error handling to catch the rejection. This can result in uncaught promise rejections, which can cause issues in your application.

When a promise is created, it can either be resolved (fulfilled) or rejected. When a promise is rejected, it means that an error or exception has occurred during the execution of the promise.

To handle promise rejections, you can use the `.catch()` method on the promise, which allows you to specify a callback function to handle the rejection. This callback function will receive the reason for the rejection as an argument.


        const promise = new Promise((resolve, reject) => {
            // Simulating an error
            reject("Something went wrong");
        });

        promise.catch((reason) => {
            console.log("Promise rejected:", reason);
        });
    

In the example above, we create a new promise that immediately rejects with the reason “Something went wrong”. Then, we use the `.catch()` method to handle the rejection and log the reason to the console.

Unhandled promise rejections can occur when the rejection is not properly handled with `.catch()`. This can happen when the `.catch()` method is not chained onto the promise, or when there are multiple promises being executed and an error occurs in one of them, but the rejection is not caught.


        const promise1 = new Promise((resolve, reject) => {
            reject("Error in promise1");
        });

        const promise2 = new Promise((resolve, reject) => {
            // Simulating an uncaught rejection
            reject("Error in promise2");
        });

        promise1.catch((reason) => {
            console.log("Promise1 rejected:", reason);
        });
    

In the example above, we have two promises – `promise1` and `promise2`. We properly handle the rejection of `promise1` using `.catch()`, but the rejection of `promise2` is unhandled. This can lead to an uncaught promise rejection error in your application.

To avoid unhandled promise rejections, it is important to always handle the rejections properly using the `.catch()` method. This way, you can handle any errors that occur during the execution of promises.

Leave a comment