đź’Ż Promises
JavaScript Promises are a mechanism to structure and handle async operation in a structured manner. They allow you to write code that responds to the result of an asynchronous task once it has completed, without running into deeply nested callbacks (also known as “callback hell”).
How ​​do Promises work?
A Promise in JavaScript is an object that represents a future value - either the successful outcome of an operation or the error that occurs during execution.
A promise can be in one of three states:
-
Pending: The promise has been created, but the result of the operation is not yet known.
- Fulfilled: The asynchronous operation was successful and the promise resolves to a value.
- Rejected: The asynchronous operation failed and the promise is rejected with an error.
Basic structure of a promise
A promise is created by the Promise
constructor, which takes a function as a parameter. This function has two arguments: resolve
and reject
. If the operation succeeds, resolve
is called, otherwise reject
.
Example: A simple promise
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("The operation was successful!");
} else {
reject("The operation failed.");
}
});
In this example, the promise checks whether success
is true. If so, the promise is resolved with the value "The operation was successful!"
, otherwise it is rejected with an error message.
Using Promises
There are two main methods for acting on the result of a promise:
-
.then()
: Called when the promise was fulfilled. -
.catch()
: Called when the promise was rejected.
Example:
myPromise
.then((message) => {
console.log(message); // "The operation was successful!"
})
.catch((error) => {
console.error(error); // "The operation failed."
});
Promise Chaining
Promises can be chained by returning a promise in the then()
method. This is useful when you want to perform multiple asynchronous operations one after the other.
Example:
const firstPromise = new Promise((resolve) => {
setTimeout(() => {
resolve("First task completed");
}, 1000);
});
firstPromise
.then((result) => {
console.log(result); // "First task completed"
return new Promise((resolve) => {
setTimeout(() => {
resolve("Second task completed");
}, 1000);
});
})
.then((result) => {
console.log(result); // "Second task completed"
})
.catch((error) => {
console.error(error);
});
Promise.all()
With Promise.all()
you can execute multiple promises at once. It waits for all promises to either be fulfilled or returns an error if any of the promises are rejected.
Example:
const promise1 = Promise.resolve("Promise 1 completed");
const promise2 = new Promise((resolve) => setTimeout(resolve, 2000, "Promise 2 completed"));
Promise.all([promise1, promise2])
.then((results) => {
console.log(results); // ["Promise 1 completed", "Promise 2 completed"]
})
.catch((error) => {
console.error(error);
});
Promise.race()
Promise.race()
returns the promise that is either fulfilled or rejected first.
Example:
const slowPromise = new Promise((resolve) => setTimeout(resolve, 3000, "Slow operation"));
const fastPromise = new Promise((resolve) => setTimeout(resolve, 1000, "Fast operation"));
Promise.race([slowPromise, fastPromise])
.then((result) => {
console.log(result); // "Fast operation"
})
.catch((error) => {
console.error(error);
});
Here the promise that is completed the fastest wins, in this case fastPromise
.
Summary:
Promises are a powerful tool for managing asynchronous operations in JavaScript. They provide a cleaner and more maintainable alternative to callbacks and improve the structure of code, especially for complex operations. Promises allow asynchronous code to be written in a more concise and structured manner, especially when combined with chaining and methods such as Promise.all()
and Promise.race()
.