π¨The Unbelievable Power of Promises: Async Mastery Unlocked! π¨
Dharmendra Kumar
Posted on September 17, 2024
Promises are at the core of modern JavaScript's ability to handle asynchronous tasks. Whether you're waiting for a server response, reading a file, or processing data, mastering promises will change the way you code. Letβs explore all types of promises and their various use cases with practical examples using axios
and fetch
! π
π 1. The Basics: HTTP GET with Promises
-
What it is: The simplest way to use a promise is with HTTP requests. When you fetch data from a server using
axios
orfetch
, you get a promise in return. - Why it matters: Fetching data asynchronously keeps your app responsive while the data is loading in the background.
Example with Axios:
axios.get('https://api.example.com/users')
.then(response => console.log(response.data))
.catch(error => console.error(error));
Example with Fetch:
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Example Output:
[
{ "id": 1, "name": "John Doe", "email": "john@example.com" },
{ "id": 2, "name": "Jane Doe", "email": "jane@example.com" }
]
π 2. Async/Await β "Asynchronous Tasks Made Easy!"
-
What it is:
async
andawait
are syntax sugars built on top of promises. They make handling asynchronous code look and feel more like synchronous code, improving readability. - Why it matters: It makes promise chains easier to read and manage, especially when dealing with multiple asynchronous operations.
Example with Axios:
async function getUsers() {
try {
const response = await axios.get('https://api.example.com/users');
console.log(response.data);
} catch (error) {
console.error(error);
}
}
getUsers();
Example with Fetch:
async function getUsers() {
try {
const response = await fetch('https://api.example.com/users');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
getUsers();
Example Output:
[
{ "id": 1, "name": "John Doe", "email": "john@example.com" },
{ "id": 2, "name": "Jane Doe", "email": "jane@example.com" }
]
π οΈ 3. Creating a New Promise β "DIY Async Handling!"
-
What it is: You can create your own promises using the
new Promise()
constructor. This is helpful when you want to control how and when a promise resolves or rejects. - Why it matters: Sometimes you need more control over your asynchronous processes, like wrapping callback-based APIs.
Example with New Promise:
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed.");
}
});
myPromise
.then(result => console.log(result))
.catch(error => console.error(error));
Example Output:
Operation was successful!
π 4. Promise.all β "Handle Multiple Promises Like a Pro!"
-
What it is:
Promise.all()
takes an array of promises and resolves them all at once. It only resolves when all promises succeed, and it rejects if any promise fails. - Why it matters: This is perfect for tasks that require multiple independent async operations, like fetching data from different endpoints.
Example with Axios:
Promise.all([
axios.get('https://api.example.com/users'),
axios.get('https://api.example.com/posts')
])
.then(([usersResponse, postsResponse]) => {
console.log(usersResponse.data);
console.log(postsResponse.data);
})
.catch(error => console.error(error));
Example with Fetch:
Promise.all([
fetch('https://api.example.com/users').then(response => response.json()),
fetch('https://api.example.com/posts').then(response => response.json())
])
.then(([users, posts]) => {
console.log(users);
console.log(posts);
})
.catch(error => console.error('Error:', error));
Example Output:
{
"users": [
{ "id": 1, "name": "John Doe" },
{ "id": 2, "name": "Jane Doe" }
],
"posts": [
{ "id": 101, "title": "Post 1" },
{ "id": 102, "title": "Post 2" }
]
}
β³ 5. Promise.race β "Only the Fastest Wins!"
-
What it is:
Promise.race()
resolves or rejects as soon as any of the promises in the array is settled, either resolved or rejected. - Why it matters: It's useful when you want the result of the fastest promise, such as fetching data from multiple APIs and using the quickest response.
Example with Axios:
Promise.race([
axios.get('https://api.example.com/users'),
axios.get('https://backup.example.com/users')
])
.then(response => console.log(response.data))
.catch(error => console.error(error));
Example with Fetch:
Promise.race([
fetch('https://api.example.com/users').then(response => response.json()),
fetch('https://backup.example.com/users').then(response => response.json())
])
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Example Output:
[
{ "id": 1, "name": "John Doe", "email": "john@example.com" }
]
π 6. Promise.any β "Only the First Successful One!"
-
What it is:
Promise.any()
resolves once any promise in the array succeeds. It ignores any rejected promises, only failing if all promises reject. - Why it matters: This is handy when you just need one successful result out of multiple attempts, such as trying multiple APIs.
Example with Axios:
Promise.any([
axios.get('https://api.example.com/slow-api'),
axios.get('https://api.example.com/faster-api'),
axios.get('https://api.example.com/fastest-api')
])
.then(response => console.log(response.data))
.catch(error => console.error(error));
Example with Fetch:
Promise.any([
fetch('https://api.example.com/slow-api').then(response => response.json()),
fetch('https://api.example.com/faster-api').then(response => response.json()),
fetch('https://api.example.com/fastest-api').then(response => response.json())
])
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Example Output:
{
"id": 1,
"name": "Fastest API Response",
"status": "Success"
}
π₯ 7. Promise.resolve & Promise.reject β "Instant Promise Creation!"
-
What it is:
Promise.resolve()
instantly returns a resolved promise, whilePromise.reject()
returns a rejected one. - Why it matters: Use these to simulate async operations, like when you need to create resolved or rejected promises for testing purposes.
Example with Promise.resolve:
Promise.resolve('Data loaded successfully!')
.then(data => console.log(data));
Example with Promise.reject:
Promise.reject('Failed to load data.')
.catch(error => console.error(error));
Example Output:
Data loaded successfully!
Failed to load data.
π― Conclusion:
Promises provide an elegant solution for managing asynchronous code. From handling simple HTTP requests with axios
or fetch
to managing complex workflows with Promise.all
, Promise.race
, and Promise.any
, understanding promises will make you a more effective and productive developer. Use async/await
to simplify your code even further, and take control over your asynchronous logic with custom promises! πͺ
Happy coding! π
Posted on September 17, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.