User Tools

Site Tools


java-script:fetch-using-async-await

Fetch using async/await

Introduction

Async/Await is part of the ES2017 specification and provides a more streamlined syntax for dealing with promises, leading to cleaner, easier-to-read code.
Async/Await uses JavaScript fetch API (which returns promises) for making HTTP requests.
The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need for explicitly chaining promises. These keywords make the asynchronous code look and behave like synchronous code.

Async/Await may not be supported in all browsers (although it is supported in most modern browsers), and you may need to use a tool like Babel to transpile your code for older browser support.

Advantages over AJAX

Async/Await in JavaScript, which is often used with the Fetch API for making HTTP requests, has several advantages over traditional AJAX techniques:

  1. Readability: Async/Await makes asynchronous code look and behave more like synchronous code. This makes the code cleaner and easier to understand.
  2. Error Handling: With Async/Await, you can use classic try/catch blocks for error handling, which is more straightforward and intuitive compared to handling errors in callbacks or promise chains.
  3. Avoiding Callback Hell: With AJAX and callbacks, code can become nested and complicated very quickly, a situation often referred to as “callback hell”. This is avoided with async/await, since each step in an async function appears to be a linear, sequential operation, not a nested one.
  4. Improved Debugging: Debugging async/await code is simpler than debugging promises or callbacks. Each async function operates as a smaller self-contained unit which can be stepped through with debugging tools.
  5. Concurrency Control: Async/Await makes it easier to control concurrency. For example, with Promise.all() and async/await, you can start several asynchronous tasks all at once and then await them all, which can lead to performance improvements.

Fetch example using async/await (web browser)

We'll use the same example, but with async/await framework instead of ajax:

fetch-async-await.html
<!DOCTYPE html>
<html>
<body>
    <div id="data"></div>
    <script>
        async function fetchData() {
            try {
                const response = await fetch('https://api.github.com/users');
                const data = await response.json();
 
                data.forEach(user => {
                    const div = document.getElementById('data');
                    div.innerHTML += `
                        <img src="${user.avatar_url}" alt="${user.login}'s avatar" width="100"><br>
                        Login: ${user.login}<br>
                        ID: ${user.id}<br>
                        Node ID: ${user.node_id}<br>
                        Avatar URL: ${user.avatar_url}<br>
                        Gravatar ID: ${user.gravatar_id}<br>
                        URL: ${user.url}<br>
                        HTML URL: ${user.html_url}<br>
                        Followers URL: ${user.followers_url}<br>
                        Following URL: ${user.following_url}<br>
                        Gists URL: ${user.gists_url}<br>
                        Starred URL: ${user.starred_url}<br>
                        Subscriptions URL: ${user.subscriptions_url}<br>
                        Organizations URL: ${user.organizations_url}<br>
                        Repos URL: ${user.repos_url}<br>
                        Events URL: ${user.events_url}<br>
                        Received Events URL: ${user.received_events_url}<br>
                        Type: ${user.type}<br>
                        Site Admin: ${user.site_admin}<br>
                        <hr>
                    `;
                });
            } catch (error) {
                console.error('Error:', error);
            }
        }
 
        fetchData();
    </script>
</body>
</html>
java-script/fetch-using-async-await.txt · Last modified: 2023/08/03 14:27 by odefta