Middle
Tell me what a Promise is in JavaScript.
sobes.tech AI
Answer from AI
A Promise in JavaScript is an object that represents the result of an asynchronous operation and allows you to work with it when the operation completes (successfully or with an error). A Promise can be in one of three states: pending, fulfilled, or rejected.
Example of using a Promise:
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));
Promises help avoid "callback hell" and simplify reading and handling asynchronous code.