Asynchronous JavaScript
How JavaScript waits for slow things — like loading data — without freezing. Essential for every real app.
What you will learn
- Understand why async exists
- Use Promises and async/await
- Handle success and errors
Why async?
Some tasks take time — fetching data from a server, reading a file. JavaScript does not freeze waiting; it carries on and handles the result when it arrives. This is asynchronous code.
Promises and async/await
A Promise represents a future result. The modern way to use one is async/await: mark a function async, then await the result as if it were normal code.
<p id="out">Loading...</p>
<script>
// A fake "slow task" that resolves after 1 second
function getData() {
return new Promise(resolve => {
setTimeout(() => resolve("Data arrived! ✅"), 1000);
});
}
async function load() {
const result = await getData(); // wait for it, without freezing
document.getElementById("out").textContent = result;
}
load();
</script>getData() returns a Promise — a placeholder for a value that is not ready yet. Here setTimeout makes it pretend to take 1 second before it resolves with the message. In load(), await getData() pauses just that function until the Promise finishes, then stores the result and shows it. Meanwhile the page stayed responsive — it was never frozen.
Follow the async flow step by step:
getData()is called and immediately returns a Promise — a "I will have a value later" placeholder.- Inside it,
setTimeoutschedules theresolve("Data arrived! ✅")to run after 1 second; until then the Promise is pending. - In
load(),await getData()pauses just this function and waits for that Promise to finish — but the rest of the page keeps running. - After
1 second the Promise resolves,awaithands the message back, and it is stored inresult~. - The final line writes
resultinto the paragraph, so "Loading..." is replaced with "Data arrived! ✅".
Note: Output: At first: Loading... After ~1 second: Data arrived! ✅
Watch out: You can only use await inside an async function. Wrap your awaiting code in an async function.
Tip: Mental model: await pauses that function until the result is ready, while the rest of the page keeps running. It reads top-to-bottom like normal code — far clearer than older callback styles.
Q. The await keyword can only be used inside a function marked with:
✍️ Practice
- Make a function that resolves a Promise after 2 seconds and
awaitit. - Add a “Loading…” message that updates when the async result arrives.
🏠 Homework
- Read about why freezing the UI is bad, and write two real examples of slow tasks that need async.