User Tools

Site Tools


java-script:fetch-using-async-await

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
java-script:fetch-using-async-await [2023/08/03 14:17] odeftajava-script:fetch-using-async-await [2023/08/03 14:27] (current) odefta
Line 1: Line 1:
 ====== 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 is part of the ES2017 specification and provides a more streamlined syntax for dealing with **promises**, leading to cleaner, easier-to-read code. \\
Line 5: Line 7:
  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.  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.
 <note> <note>
-However, 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 **[[java-script:babel|Babel]]** to transpile your code for older browser support.+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 **[[java-script:babel|Babel]]** to transpile your code for older browser support.
 </note> </note>
 +
 +===== Advantages over AJAX =====
 +
 +Async/Await in JavaScript, which is often used with the Fetch API for making HTTP requests, has several advantages over traditional **[[java-script:ajax-fetch|AJAX]]** techniques:
 +
 +  - **Readability**: Async/Await makes asynchronous code look and behave more like synchronous code. This makes the code cleaner and easier to understand.
 +  - **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.
 +  - **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.
 +  - **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.
 +  - **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 [[java-script:ajax-fetch|same example]], but with async/await framework instead of ajax:
 +
 +<code javascript 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>
 +</code>
 +
  
  
  
java-script/fetch-using-async-await.1691061424.txt.gz · Last modified: 2023/08/03 14:17 by odefta