Javascript Async/Await and Fetch API

Async/Await:

The async/await syntax allows you to write asynchronous code in a more synchronous style, making it easier to understand and maintain. Here’s a step-by-step breakdown with an example:

  • Declare an asynchronous function using the async keyword.
  • Inside the function, use the await keyword before promises to pause the execution until the promise is resolved or rejected.
  • Handle errors using the try/catch block to gracefully manage promise rejections.

Example: Using async/await with Fetch API:

Suppose you have an API that provides information about users. Let’s fetch user data using the Fetch API and async/await:

async function fetchUserData(userId) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
const user = await response.json();
return user;
} catch (error) {
console.error('Error:', error);
throw error; // Re-throw the error for further handling
}
}

async function main() {
try {
const userId = 1;
const user = await fetchUserData(userId);
console.log('User:', user);
} catch (error) {
console.error('Main Error:', error);
}
}

main();

In this example:

  • The fetchUserData function fetches user data from a JSON API using the Fetch API and returns the parsed JSON data.
  • The main function demonstrates how to use async/await with the fetchUserData function. It calls fetchUserData, awaits the result, and logs the user data. If an error occurs, it’s caught and handled using the catch block.

Fetch API:

The Fetch API is a modern way to perform network requests. It returns a promise that resolves to the response to that request. Here’s how it works:

  • Call the fetch function with the URL you want to request.
  • Chain .then() to process the response when the promise is resolved.
  • Use .catch() to handle errors if the promise is rejected.

Example: Using Fetch API without async/await:

fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(post => console.log('Post:', post))
.catch(error => console.error('Error:', error));

In this example:

  • The fetch function is used to request data from the API.
  • The .then() method chains parsing of the response and logging the post data.
  • The .catch() method handles errors if the request fails.

Combining async/await and the Fetch API can make asynchronous code easier to write and understand, especially when dealing with complex sequences of asynchronous operations and error handling.

You can also discover a lot about Javascript by exploring different topics.

Note: We welcome your feedback at Easy coding School. Please don’t hesitate to share your suggestions or any issues you might have with the article!

Leave a Reply

Your email address will not be published. Required fields are marked *