Using async in jQuery for making API calls can streamline your asynchronous operations, making the code more readable and easier to manage. This article will guide you through the steps of using async and await in jQuery to call an API using Ajax.

Prerequisites

Why Use async and await?

Before diving into the implementation, let's understand why you might want to use async and await.

Setup your HTML Page

Create a basic HTML page that includes jQuery.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Async/Await with jQuery Ajax</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <button id="fetchData">Fetch Data</button>
    <div id="result"></div>
    <script src="script.js"></script>
</body>
</html>

Create your JavaScript file

Create a script.js file where you will write the JavaScript code.

$(document).ready(function() {
    $('#fetchData').click(async function() {
        try {
            const data = await fetchData();
            displayData(data);
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    });
});
async function fetchData() {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: 'https://api.example.com/data', // Replace with your API URL
            method: 'GET',
            success: function(response) {
                resolve(response);
            },
            error: function(xhr, status, error) {
                reject(error);
            }
        });
    });
}
function displayData(data) {
    $('#result').html(JSON.stringify(data));
}

Explanation

  1. HTML Setup
    • The HTML file includes a button to fetch data and a div to display the result.
    • jQuery is included using a CDN link.
  2. JavaScript with async and await
    • $(document).ready: Ensures the DOM is fully loaded before attaching the click event handler to the button.
    • Event Handler: The click event handler on the button calls an asynchronous function to fetch data.
    • fetchData Function: This function uses jQuery's $.ajax method wrapped in a Promise. It makes a GET request to the specified API URL.
      • resolve(response): On a successful response, the Promise is resolved with the response data.
      • reject(error): On error, the Promise is rejected with the error message.
    • displayData Function: This function updates the HTML content of the #result div with the fetched data.

Benefits of this Approach

Conclusion

Using async and await in jQuery when making API calls with Ajax enhances the readability and maintainability of your code. This approach simplifies asynchronous programming, making it easier to handle API responses and errors. Try implementing this in your projects to experience the benefits firsthand.