====== 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 **[[java-script:babel|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 **[[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: