java-script:fetch-using-async-await
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
java-script:fetch-using-async-await [2023/08/03 14:21] – odefta | java-script:fetch-using-async-await [2023/08/03 14:27] (current) – odefta | ||
---|---|---|---|
Line 15: | Line 15: | ||
- **Readability**: | - **Readability**: | ||
- | |||
- **Error Handling**: With Async/ | - **Error Handling**: With Async/ | ||
- | |||
- **Avoiding Callback Hell**: With AJAX and callbacks, code can become nested and complicated very quickly, a situation often referred to as " | - **Avoiding Callback Hell**: With AJAX and callbacks, code can become nested and complicated very quickly, a situation often referred to as " | ||
- | |||
- **Improved Debugging**: | - **Improved Debugging**: | ||
- | |||
- **Concurrency Control**: Async/Await makes it easier to control concurrency. For example, with Promise.all() and async/ | - **Concurrency Control**: Async/Await makes it easier to control concurrency. For example, with Promise.all() and async/ | ||
+ | |||
+ | ===== Fetch example using async/await (web browser) ===== | ||
+ | |||
+ | We'll use the [[java-script: | ||
+ | |||
+ | <code javascript fetch-async-await.html> | ||
+ | < | ||
+ | < | ||
+ | < | ||
+ | <div id=" | ||
+ | < | ||
+ | async function fetchData() { | ||
+ | try { | ||
+ | const response = await fetch(' | ||
+ | const data = await response.json(); | ||
+ | |||
+ | data.forEach(user => { | ||
+ | const div = document.getElementById(' | ||
+ | div.innerHTML += ` | ||
+ | <img src=" | ||
+ | Login: ${user.login}< | ||
+ | ID: ${user.id}< | ||
+ | Node ID: ${user.node_id}< | ||
+ | Avatar URL: ${user.avatar_url}< | ||
+ | Gravatar ID: ${user.gravatar_id}< | ||
+ | URL: ${user.url}< | ||
+ | HTML URL: ${user.html_url}< | ||
+ | Followers URL: ${user.followers_url}< | ||
+ | Following URL: ${user.following_url}< | ||
+ | Gists URL: ${user.gists_url}< | ||
+ | Starred URL: ${user.starred_url}< | ||
+ | Subscriptions URL: ${user.subscriptions_url}< | ||
+ | Organizations URL: ${user.organizations_url}< | ||
+ | Repos URL: ${user.repos_url}< | ||
+ | Events URL: ${user.events_url}< | ||
+ | Received Events URL: ${user.received_events_url}< | ||
+ | Type: ${user.type}< | ||
+ | Site Admin: ${user.site_admin}< | ||
+ | <hr> | ||
+ | `; | ||
+ | }); | ||
+ | } catch (error) { | ||
+ | console.error(' | ||
+ | } | ||
+ | } | ||
+ | |||
+ | fetchData(); | ||
+ | </ | ||
+ | </ | ||
+ | </ | ||
+ | </ | ||
+ | |||
java-script/fetch-using-async-await.1691061711.txt.gz · Last modified: 2023/08/03 14:21 by odefta