Middle+
What is a Promise? What states does a Promise have?
sobes.tech AI
Answer from AI
Promise is an object in JavaScript/Node.js that represents the result of an asynchronous operation, which may succeed or fail in the future.
A Promise has three main states:
- pending: initial state, the operation is not yet completed.
- fulfilled: the operation completed successfully, and the Promise contains the result.
- rejected: the operation failed with an error.
Promises allow writing asynchronous code more readably, using .then() methods to handle success and .catch() for errors. The async/await syntax is also supported for more convenient asynchronous management.
Example:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve('Data received');
} else {
reject('Error');
}
}, 1000);
});
promise
.then(data => console.log(data))
.catch(error => console.error(error));