Using async/await instead of .then() and .catch() makes the code cleaner, and thus easier to understand.
Lets look at an example using async/await and try/catch:
In the above example,
-
We use fetch() to make an asynchronous request to the JSONPlaceholder API and await its response.
-
The response.json() method parses the response into JSON format, and the data is logged to the console.
-
If an error occurs at any stage like network issues or invalid URLs, the catch block handles it, and the error message is logged.
From now on, we will consistently use async/await to handle asynchronous operations as it makes the code more readable and easier to work with.