JavaScript Advanced: Closures, Async and Modules
Promises and async/await
In this lesson you will
- Explain what a promise is and its three states
- Use then, catch and finally
- Write asynchronous code with async and await
Introduction
Some things take time: loading data from a server, reading a file, waiting for a timer. JavaScript must not freeze the whole page while it waits. It starts the task, carries on, and handles the result later. Promises are the modern way to describe that.
The simple explanation
A promise is a placeholder for a value that will be available later.
Think of an order at a restaurant. You get a buzzer (the promise). The food is not ready, but you are free to do other things. Soon the buzzer goes off: either your food is ready, or the kitchen has a problem.
A promise is always in one of three states:
- pending: still waiting.
- fulfilled: finished successfully, with a value.
- rejected: failed, with a reason.
Quick quiz
Which is NOT a state of a promise?
Making and using a promise
Notice the order: the last line prints before the result. .then runs when the promise is fulfilled.
Errors with catch and finally
catch handles a rejection, and finally runs either way. You can chain .then calls, and each one receives the previous result.
async and await
async/await is a clearer way to write the same thing. It lets asynchronous code read from top to bottom.
- Put
asyncbefore a function. It then always returns a promise. - Inside it,
awaitpauses that function until a promise settles, and gives you its value. The rest of the program keeps running.
Errors with try and catch
With await, use try/catch, just like with normal code.
Quick quiz
What does await do?
Running tasks together
Awaiting one task after another is slow if they do not depend on each other. Promise.all starts them together and waits for all of them.
It takes about 200ms in total (the longest task), not 450ms. If any promise rejects, Promise.all rejects too. Promise.allSettled waits for all and tells you each outcome.
Try it yourself
Write an async function loadAll() that awaits getName() and then getAge() in order and prints a sentence. Then change it to run both at the same time with Promise.all.
Summary
- A promise represents a future value: pending, fulfilled or rejected.
.then,.catchand.finallyreact to the result.async/awaitmakes asynchronous code read like normal code. Usetry/catchfor errors.Promise.allruns independent tasks together.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading