Promises help write cleaner, more readable, and maintainable asynchronous code.
A JavaScript Promise can be in one of three states:
Once a Promise is fulfilled or rejected, it is settled and cannot change state.
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation successful");
} else {
reject("Operation failed");
}
});
myPromise
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});
fetchData()
.then(data => processData(data))
.then(result => saveResult(result))
.catch(error => console.error(error));
Promise.all([promise1, promise2])
.then(results => {
console.log(results);
})
.catch(error => console.error(error));
| Feature | Callbacks | Promises |
|---|---|---|
| Readability | Low (nested) | High (chained) |
| Error Handling | Complex | Simple (.catch) |
| Modern Usage | Less Preferred | Widely Used |
async function getData() {
try {
const result = await myPromise;
console.log(result);
} catch (error) {
console.error(error);
}
}