Middle+
What is a Promise in JavaScript? Describe the states of a promise and how to work with it.
sobes.tech AI
Answer from AI
Promise in JavaScript is an object representing the result of an asynchronous operation that may complete successfully or with an error in the future.
States of a promise:
- pending — initial state, the operation is not yet completed.
- fulfilled — the operation completed successfully, and there is a result.
- rejected — the operation finished with an error.
Main methods for working with Promise:
.then(onFulfilled, onRejected)— adds handlers for successful and erroneous completion..catch(onRejected)— adds an error handler (equivalent to.then(null, onRejected))..finally(onFinally)— executes a function after the promise is settled, regardless of the result.
Example:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve('Data received');
} else {
reject('Error');
}
}, 1000);
});
promise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log('Operation completed'));