Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptDifferent error handling in “Promise.resolve” vs “new Promise” constructor

Different error handling in “Promise.resolve” vs “new Promise” constructor

In JavaScript, there are two ways to create a promise: using the Promise.resolve method or using the new Promise constructor. While both ways achieve the same result, they handle errors differently.

Promise.resolve: The Promise.resolve method takes in a value and returns a promise that is resolved with that value. If the value is a promise, the returned promise will take on the state of that promise. If the value is a thenable (i.e. has a .then method), the returned promise will adopt the state of the thenable.

If the value passed into Promise.resolve is not a promise or thenable, the returned promise will be resolved with the value.

Promise.resolve is often used when you don’t know if the value is a promise or not, or when you want to ensure that the returned promise is always resolved.

To handle errors with Promise.resolve, you can pass in a function as the second argument. This function will be called if the promise is rejected.

Example: Below is the full working code for Promise.resolve with error handling:

Javascript




Promise.resolve('value').then(function (value) {
    console.log("Resolved")
}).catch(function (error) {
    console.log("Error")
});


Output:

Resolved

new Promise: The new Promise constructor takes in a function as an argument. This function is called with two arguments: resolve and reject. The resolve function is used to resolve the promise with a value, and the reject function is used to reject the promise with an error.

If you want to handle errors with the new Promise constructor, you only need to pass in the reject function. The resolve function is optional.

Example: Below is the full working code for the new Promise constructor with error handling:

Javascript




new Promise(function (resolve, reject) {
    var a = 1
  
    if (a == 2) {
        resolve('value');
    } else {
        reject('error');
    }
}).catch(function (error) {
    console.log("Error is resolved")
});


Output:

Error is resolved

While both Promise.resolve and the new Promise constructor achieve the same result, they handle errors differently. Promise.resolve will always return a promise that is resolved, even if the value passed in is a promise that is rejected. The new Promise constructor will only return a promise that is rejected if the reject function is called.

If you’re not sure if the value is a promise or not, or if you want to ensure that the returned promise is always resolved, use Promise.resolve. If you want to handle errors with the new Promise constructor, you only need to pass in the reject function.

RELATED ARTICLES

Most Popular

Recent Comments