New promise resolve reject
A fundamental concept in JavaScript!
A Promise
is a result object that is used to handle asynchronous operations. It has three states:
- Pending: Initial state, where the promise is waiting for its operation to complete.
- Fulfilled: The operation has completed successfully, and the promise has a value.
- Rejected: The operation has failed, and the promise has an error.
When a promise is created, it can be resolved or rejected. Here's what happens:
Resolve:
- A promise is resolved when its operation completes successfully.
- The promise is moved to the "Fulfilled" state.
- The promise's
then()
method is called with the resolved value as an argument. - The
then()
method returns a new promise that is resolved with the same value.
Example:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Hello, world!"); // Resolve the promise with a value
}, 2000);
});
promise.then((value) => {
console.log(value); // Output: "Hello, world!"
});
Reject:
- A promise is rejected when its operation fails.
- The promise is moved to the "Rejected" state.
- The promise's
catch()
method is called with the rejected error as an argument. - The
catch()
method returns a new promise that is rejected with the same error.
Example:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error("Something went wrong")); // Reject the promise with an error
}, 2000);
});
promise.catch((error) => {
console.error(error); // Output: Error: Something went wrong
});
Chaining promises:
You can chain multiple promises together using the then()
method. Each then()
method returns a new promise that is resolved or rejected based on the outcome of the previous promise.
Example:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Hello, world!"); // Resolve the promise with a value
}, 2000);
});
promise.then((value) => {
console.log(value); // Output: "Hello, world!"
return value.toUpperCase(); // Return a new promise that resolves with the uppercase value
}).then((uppercaseValue) => {
console.log(uppercaseValue); // Output: "HELLO, WORLD!"
});
In this example, the first then()
method resolves the promise with the value "Hello, world!". The second then()
method is called with the resolved value, and it returns a new promise that resolves with the uppercase value "HELLO, WORLD!".