Mastering JavaScript Promises ๐
Promises in JavaScript are a way to handle asynchronous operations. They can be in one of three states:
- Pending: The Promise is still running and hasn't resolved yet.
- Fulfilled: The Promise has finished and it was successful.
- Rejected: The Promise has finished and it was unsuccessful.
Here's a simple example of a Promise:
let promise = new Promise(function(resolve, reject) {
// some code
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
In the above code, resolve
and reject
are functions provided by the Promise constructor. We call resolve
when we want to indicate that the Promise was successful, and reject
when something went wrong.
To handle the result of a Promise, we use .then
for a successful Promise, and .catch
for a failed Promise:
promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});
Or, you can separate the success and failure handlers:
promise
.then(function(result) {
console.log(result); // "Stuff worked!"
})
.catch(function(err) {
console.log(err); // Error: "It broke"
});
Promises are a powerful tool in JavaScript, allowing us to write asynchronous code that is easier to understand and manage. Mastering Promises will make your web development journey much smoother! ๐