Middle
How does Promise work in JavaScript?
sobes.tech AI
Answer from AI
- An object representing a possible final completion (or failure) of an asynchronous operation and its resulting value.
- Promise states:
pending: initial state, neither fulfilled nor rejected.fulfilled: indicates that the operation completed successfully.rejected: indicates that the operation failed.
- Transition from
pendingtofulfilledorrejectedoccurs once and is irreversible. - Methods:
.then(onFulfilled, onRejected): Takes two callback functions. The first (onFulfilled) is called upon success, the second (onRejected) upon failure. Both arguments are optional. Returns a new promise..catch(onRejected): Short for.then(null, onRejected). Used for error handling. Returns a new promise..finally(onFinally): Called regardless of the promise's outcome (success or failure). Useful for resource cleanup. Returns a new promise.
- Creating a promise:
new Promise((resolve, reject) => {
// Asynchronous operation
const success = true;
if (success) {
resolve("Operation successful!"); // Transition to fulfilled
} else {
reject("Something went wrong..."); // Transition to rejected
}
});
- Promise chains:
.then(),.catch(),.finally()return promises, allowing chaining for sequential asynchronous operations.
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));