Async Concepts in JavaScript
Async Concepts = code that finishes later, like timers and data from a server.
This chapter has 3 lessons and 13 exercises you run and check in your browser. Plan on about 75 minutes.
- Asynchronous Fundamentals: callbacks, timers and the event loop.
- Promises and Async/Await: promises,
async/awaitand running tasks together. - Fetch API: calling APIs with
fetch(), with a real server and client in your browser.
After this chapter, you can:
- Explain why JavaScript never waits, and predict the order of output.
- Use timers and cancel them.
- Write readable async code with promises and
await. - Call a real API, check the response, and handle every kind of failure.
Every lesson has short explanations, code boxes you edit and run in the live editor, and a web page example you can click.
Before you start, finish Error Handling.
Next chapter: Object-Oriented JavaScript.
Lessons in this section
- Asynchronous Fundamentals
What asynchronous code is and why JavaScript needs it, sync vs async behaviour, callbacks after a task and with events, callback hell, setTimeout, setInterval and how to cancel them, and the event loop with its microtask and macrotask queues.
- Explain what asynchronous code is and why JavaScript needs it
- Predict the order of synchronous and asynchronous output
- Pass callbacks to run after a task finishes or when an event happens
- Recognise callback hell and why it is hard to maintain
- Promises and Async/Await
What a promise is and its three states, creating promises with resolve() and reject(), then(), catch(), finally() and chaining, async functions and await with try...catch, fetch(), and Promise.all(), allSettled() and race().
- Explain what a promise is and name its pending, fulfilled and rejected states
- Create a promise with new Promise and settle it with resolve() or reject()
- Handle results with then(), catch() and finally(), and chain dependent steps
- Write async functions that use await and handle errors with try...catch
- Fetch API
Calling APIs with fetch(), reading status, headers and JSON, sending POST, PATCH and DELETE requests, handling HTTP and network errors, a real Hono server and client in the browser, and the most common async mistakes.
- Call an API with fetch() and read a response's status, headers and body
- Convert a response body to a JavaScript value with response.json()
- Send POST, PUT, PATCH and DELETE requests with method, headers and body
- Handle HTTP errors, network errors and bad JSON with catch() and try...catch