Promises
A concept that many developers find hard to understand at first: promises.
Promises were introduced to make handling asynchronous operations in JavaScript easier. They solve the problem that callbacks often end up deeply nested and are hard to read and maintain. Promises offer a cleaner and simpler way to run and manage asynchronous operations.
But how exactly do promises work? A promise is basically an object that performs an operation asynchronously and either returns a value or throws an error. A promise can be in one of three states:
- Pending: the initial state a promise is in when it is created.
- Fulfilled: the state in which the promise completed successfully and returned a value.
- Rejected: the state in which the promise threw an error.
Let's explain this with an example:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() >= 0.5) {
resolve("Success!");
} else {
reject("Error!");
}
}, 1000);
});
myPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
In this example we create a promise that returns either "Success!" or "Error!" after one second, depending on whether a random number is greater or less than 0.5. We then use the "then" method to handle success, or the "catch" method to handle the error.
Promises can also be chained to run complex asynchronous operations. The following example shows how to chain promises to run an asynchronous task in several steps:
function stepOne() {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Step One Complete");
resolve();
}, 1000);
});
}
function stepTwo() {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Step Two Complete");
resolve();
}, 1000);
});
}
function stepThree() {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Step Three Complete");
resolve();
}, 1000);
});
}
stepOne()
.then(() => stepTwo())
.then(() => stepThree())
.then(() => console.log("All Steps Complete"));
In this example we defined three functions that each perform an asynchronous operation and return a promise when they finish. We then call these functions one after another by chaining them with the "then" method, which makes sure each step only runs once the previous step has completed.