Promise State and Core Methods
A Promise is an object designed to handle asynchronous operations. It encapsulates asynchronous operations into a single object, allowing for more flexible handling of their results. A Promise object exists in one of three states: pending (waiting), resolved (fulfilled), or rejected. The state can only transition from pending to either resolved or rejected, and once the state is determined, it cannot be changed again.
The primary methods of a Promise object are as follows:
Promise.resolve(value)
Returns aPromiseobject in theresolvedstate, wherevaluerepresents the result of thePromise.Promise.reject(reason)
Returns aPromiseobject in therejectedstate, wherereasonrepresents the error cause of thePromise.Promise.prototype.then(onResolved, onRejected)
Adds callback functions for bothresolvedandrejectedstates.onResolvedis used to handle the successful result of thePromise, whileonRejectedhandles the failure reason. This method returns a newPromiseobject.Promise.prototype.catch(onRejected)
Adds a callback function for therejectedstate, used to handle the failure reason of thePromise. It returns a newPromiseobject.Promise.prototype.finally(onFinally)
Adds a callback function that executes regardless of whether thePromiseobject is resolved or rejected. It returns a newPromiseobject.
const promise = new Promise((resolve, reject) => {
// Execute asynchronous task
// ...
// After the asynchronous task completes, call resolve or reject method
if (success) {
resolve(data);
} else {
reject(error);
}
});
promise.then(data => {
// Use data returned by the asynchronous task
// ...
})
.catch(error => {
// Handle errors from the asynchronous task
// ...
})
.finally(() => {
// Callback function that executes regardless of the Promise object's state
// ...
});
In summary, a Promise object is an object designed to handle asynchronous operations. It encapsulates asynchronous operations into a single object, enabling more flexible handling of their results. The state of a Promise object can only transition from pending to resolved or rejected, and once the state is determined, it cannot be changed again. The primary methods of a Promise object include resolve, reject, then, catch, and finally. The most suitable method should be selected based on specific requirements and actual scenarios.