What are the differences between JavaScript's Promise.resolve() and Promise.reject()?
Richard W
In JavaScript,Promise.resolve() andPromise.reject() are methods used to create and return promises with different states. Here are the differences between these two methods:
1. Promise.resolve():
-Promise.resolve() creates a new promise that is resolved with the given value or a resolved promise if the value is already a promise.
- It returns a promise that is immediately fulfilled with the provided value.
In this example,Promise.resolve(value) creates a new promise that resolves with thevalue.
- If thevalue is a promise,Promise.resolve() returns that promise directly without any modifications.
- If thevalue is not a promise,Promise.resolve() creates a new promise that is immediately resolved with thevalue.
2. Promise.reject():
-Promise.reject() creates a new promise that is rejected with the given reason.
- It returns a promise that is immediately rejected with the provided reason.
In this example,Promise.reject(reason) creates a new promise that is rejected with thereason.
- Thereason can be any value or an error object to indicate the reason for the rejection.
3. Usage:
-Promise.resolve() is commonly used when you want to create a promise that immediately resolves with a specific value. It is useful for converting non-promise values into promises or when you want to provide a default or pre-computed result.
-Promise.reject() is useful when you want to create a promise that immediately rejects with a specific reason or error. It is commonly used for error handling or to simulate a failed promise.
4. Chaining:
- BothPromise.resolve() andPromise.reject() return promises, allowing you to chain further operations using.then() and.catch().
In this example, the returned promise fromPromise.resolve() orPromise.reject() can be further chained with.then() to handle the resolved value or with.catch() to handle the rejection or any errors that occur.
Overall,Promise.resolve() is used to create a promise that resolves with a specific value, whilePromise.reject() is used to create a promise that is immediately rejected with a specific reason or error.