Middle
What is a Promise and how does it work?
sobes.tech AI
Answer from AI
Promise is an object in JavaScript that represents the result of an asynchronous operation, which may succeed or fail in the future.
It works as a container for a value that will become available later. A Promise can be in three states:
- pending — the operation is not yet completed;
- fulfilled — the operation has successfully completed, and the value is available;
- rejected — the operation has failed with an error.
Example of usage:
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));
Thus, Promise allows writing asynchronous code, avoiding nested callbacks and improving readability.