Introductionโ
Promises in JavaScript revolutionized asynchronous programming, simplifying complex chains of callbacks. However, their power goes beyond basic usage.
In this article, we'll deive into advanced aspects of promises, focusing on promise chaining and robust error handling techniques. By mastering these concepts, you can write more elegant and robust asynchronous code.
Suggested Tutorials ๐:โ
Let's get started! ๐
1. Promise Chainingโ
Promise chaining is a powerful technique that allows you to simplify complex asynchronous code. It involves chaining multiple promises together, where the result of one promise is passed to the next promise in the chain.
Let's look at an example of promise chaining.
In this example, we'll use the fetch()
API to retrieve a list of users from a remote server. We'll then use the map()
method to extract the name
property from each user object.
Finally, we use the forEach()
method to log each name to the console.
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => users.map(user => user.name))
.then(names => names.forEach(name => console.log(name)));
In the above example:
- We chain three promises together. The first promise is returned by the
fetch()
method. - This promise resolves to a
Response
object, which we pass to thejson()
method. - This method returns a promise that resolves to a JavaScript object.
- We then pass this object to the
map()
method, which returns a new array containing thename
property of each user object. - Finally, we pass this array to the
forEach()
method, which logs each name to the console.
2. Error Handlingโ
In the previous example, we didn't handle any errors. This is a common mistake when working with promises. It's important to handle errors, as they can occur at any point in the promise chain.
Let's look at an example of error handling.
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => users.map(user => user.name))
.then(names => names.forEach(name => console.log(name)))
.catch(error => console.log(error.message));
In the above example:
- We chain four promises together. And we use the
catch()
method to handle errors. - So if any of the promises in the chain rejects, the error will be passed to the
catch()
method.
Suggested Tutorials ๐:โ
3. Promise Chaining With Async Awaitโ
async/await, providing a cleaner way to work with promises, making the code look more synchronous. It's important to note that async/await is built on top of promises. So you can use async/await with promises. In fact, async/await is just syntactic sugar for promises.
Now let's look at an example of promise chaining with async/await.
async function getUsers() {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await response.json();
const names = users.map(user => user.name);
names.forEach(name => console.log(name));
}
getUsers();
In the above example:
- We use the
async
keyword to define an asynchronous function. - Then
await
keyword to wait for the promise returned by thefetch()
method to resolve. - Then another
await
keyword to wait for the promise returned by thejson()
method to resolve. map()
method to extract thename
property from each user object.- Finally, we use the
forEach()
method to log each name to the console.
4. Error Handling With Async Awaitโ
In the previous example, we didn't handle any errors. which is not a good practice. it's always a good idea to handle errors, as they can occur at any point in the promise chain and brake your code.
async function getUsers() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await response.json();
const names = users.map(user => user.name);
names.forEach(name => console.log(name));
} catch (error) {
console.log(error.message);
}
}
getUsers();
In the above example:
- We use the
async
keyword to define an asynchronous function. - Then we use the
try
andcatch
keywords to handle errors. - If any of the promises in the chain rejects, the error will be passed to the
catch()
method.
Suggested Tutorials ๐:โ
Conclusionโ
In this article, we've explored advanced aspects of promises, focusing on promise chaining and robust error handling techniques. By mastering these concepts, you can write more elegant and robust asynchronous code. We've also looked at how to use async/await with promises. So you can use async/await with promises.
We hope you found this article useful.
Happy coding! ๐