Async/Await
by sbjami
HTML
<body>
<h1>Async/Await</h1>
<button id="fetchBtn">
Fetch data
</button>
<p id="userData">
User data goes here
</p>
<hr>
<p id="postsData">
Posts data goes here
</p>
</body>
CSS
button {
color: red;
}
JavaScript
const baseUrl = "https://jsonplaceholder.typicode.com";
const postsUrl = `${baseUrl}/posts`;
const usersUrl = `${baseUrl}/users`;
const userId = 1;
const fetchAsync = async url => {
const response = await fetch(url);
const data = await response.json();
return data;
}
document.getElementById("fetchBtn").addEventListener("click", async () => {
const userData = await fetchAsync(`${usersUrl}/${userId}`);
document.getElementById("userData").innerText = JSON.stringify(userData);
const userPosts = await fetchAsync(`${postsUrl}?userId=${userData.id}`);
document.getElementById("postsData").innerText = JSON.stringify(userPosts);
});