Why asynchronous code?
Some tasks take time: loading data from a server, reading a file, waiting for a timer. JavaScript does not freeze while waiting. It continues running other code and comes back when the result is ready.
console.log("1");
setTimeout(() => console.log("2 (after 1 second)"), 1000);
console.log("3");
// prints 1, 3, then 2Promises
A Promise represents a value that will arrive later. It is either pending, fulfilled or rejected.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
wait(500).then(() => console.log("Done")).catch(err => console.log(err));async and await
async/await makes asynchronous code read like normal code.
async function loadUser() {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/users/1");
if (!res.ok) throw new Error("Request failed: " + res.status);
const user = await res.json();
console.log(user.name);
} catch (error) {
console.log("Something went wrong:", error.message);
}
}
loadUser();Try it: fetch and display data
<button id="go">Load users</button>
<ul id="out"></ul>
<script>
document.getElementById("go").addEventListener("click", async () => {
const out = document.getElementById("out");
out.innerHTML = "Loading...";
try {
const res = await fetch("https://jsonplaceholder.typicode.com/users?_limit=5");
const users = await res.json();
out.innerHTML = "";
users.forEach(u => {
const li = document.createElement("li");
li.textContent = u.name + " - " + u.email;
out.appendChild(li);
});
} catch (e) {
out.textContent = "Could not load data.";
}
});
</script>Running things in parallel
const [a, b] = await Promise.all([fetch(urlA), fetch(urlB)]);Good practice
- Always handle errors with
tryandcatch. - Show a loading state and an error message to users.
- Never put secret keys in front-end JavaScript. Anyone can read them.
Practice
Fetch a list of posts from a public API and show the first ten titles. Add a search box that filters them as you type.
Next steps
You now know the core of the web. Continue with the Full Stack Development course to connect a front end to a back end.