Async JavaScript — Promises, async/await and fetch
The event loop, callbacks, promises, async/await, calling APIs with fetch, and handling errors and loading states.
Waiting for a Network Response Is Not Instant
A browser must remain responsive while work is pending. A network request, timer, or file operation may take much longer than a simple calculation. JavaScript starts that work and continues processing other events rather than blocking the page until the result is ready. This is asynchronous programming.
The event loop coordinates synchronous code with queued callbacks and promise reactions. It does not mean every task runs simultaneously on another JavaScript thread. The important practical lesson is that the order of output can differ from the order in which work was started.
console.log('First: start')
setTimeout(() => console.log('Third: timer callback'), 0)
console.log('Second: current code finishes')A callback is a function passed to another operation so it can be called later. Callbacks are useful, but chaining many nested callbacks can obscure the sequence and error handling. Promises provide a standard representation of an operation that may succeed or fail later.
A Promise Represents a Future Result
A promise starts pending, then settles as fulfilled with a value or rejected with a reason. .then()handles success, .catch() handles rejection, and .finally() runs cleanup regardless of outcome. Each .then() returns another promise, so returning a promise from a handler keeps the chain connected.
function wait(milliseconds) {
return new Promise((resolve) => {
setTimeout(() => resolve('Finished waiting'), milliseconds)
})
}
wait(300).then((message) => {
console.log(message)
}).catch((error) => {
console.error('Wait failed:', error)
}).finally(() => {
console.log('Cleanup runs either way')
})A common promise-chain bug is forgetting to return a request from a handler. The next step then receivesundefined instead of waiting for the request. Return the promise you want the chain to await.
getCourse()
.then((course) => {
return getLessons(course.id) // return keeps this request in the chain
})
.then((lessons) => {
console.log(lessons)
})
.catch((error) => {
console.error('Could not load course data:', error)
})Write Asynchronous Sequences in a Straight Line
An async function always returns a promise. Inside it, await pauses that function until a promise settles; it does not block the entire browser. The syntax makes ordered steps easier to read, especially when later work depends on earlier results.
function loadCourseSummary() {
return Promise.resolve({ title: 'JavaScript', lessonCount: 6 })
}
async function showSummary() {
const course = await loadCourseSummary()
console.log(course.title, course.lessonCount)
}
showSummary().catch((error) => console.error(error))Use try / catch around awaited operations that can reject. Handle the failure close to the UI state it affects, or rethrow it when a higher layer can make a better decision. A function should not silently pretend a failed request succeeded.
async function loadProfile() {
try {
const profile = await getProfile()
return profile
} catch (error) {
console.error('Profile request failed')
throw error
}
}Independent requests can run together. Use Promise.all() when all results are required; if one rejects, the combined promise rejects. If each result should be handled separately, consider Promise.allSettled()and make the partial-success behaviour explicit.
async function loadDashboard() {
const [courses, announcements] = await Promise.all([
getCourses(),
getAnnouncements(),
])
return { courses, announcements }
}Send a Request and Check the Response
The browser's fetch() function sends an HTTP request and resolves to a Response when a response arrives. That does not mean the request succeeded: HTTP error statuses such as not found or server error still produce a response. Check response.ok before parsing a success payload.
| Step | What to do | Why it matters |
|---|---|---|
| Request | Call fetch with a URL and options as needed | Method, headers, and body describe the request |
| Status | Check response.ok or response.status | fetch does not reject for ordinary HTTP error statuses |
| Body | Await response.json() or another body reader | Reading the response body is asynchronous too |
| UI | Render data or an error state | Users need feedback for every outcome |
async function fetchCourses() {
const response = await fetch('/api/courses')
if (!response.ok) {
throw new Error('Courses request failed with status ' + response.status)
}
return response.json()
}
fetchCourses()
.then((courses) => console.log(courses))
.catch((error) => console.error(error.message))Parsing JSON can also fail if the server response is not valid JSON. The content type and API contract should be understood rather than guessed. When sending JSON, set a JSON content type and serialize an object withJSON.stringify(). Do not send secrets from browser code: anything delivered to a browser can be inspected by its user.
Show Loading, Success, Empty, and Error States
A page that fetches a list should describe its current state. Clear stale errors before starting, show progress, and always stop the loading indicator in a finally block. Distinguish an empty result from a failed request; those are different situations and need different messages.
const statusMessage = document.querySelector('#course-status')
const courseList = document.querySelector('#course-list')
async function renderCourses() {
statusMessage.textContent = 'Loading courses…'
courseList.replaceChildren()
try {
const response = await fetch('/api/courses')
if (!response.ok) {
throw new Error('Request failed (' + response.status + ')')
}
const courses = await response.json()
if (!Array.isArray(courses)) {
throw new Error('Unexpected response format')
}
if (courses.length === 0) {
statusMessage.textContent = 'No courses are available yet.'
return
}
for (const course of courses) {
const item = document.createElement('li')
item.textContent = course.title
courseList.append(item)
}
statusMessage.textContent = 'Courses loaded.'
} catch (error) {
statusMessage.textContent = 'Could not load courses. Try again.'
console.error(error)
}
}The example checks that the top-level result is an array, but a real client should also validate each required course field. It renders titles with textContent so API text is not parsed as HTML. The catch shows a friendly message while logging enough detail for a developer to investigate.
- Set loading feedback and clear or preserve old data intentionally.
- Await fetch and check the HTTP status.
- Parse the body and validate its shape.
- Render success or empty content using safe DOM APIs.
- Handle errors and use finally for shared cleanup when needed.
Send JSON with the Correct Method and Headers
To create a record, use the method expected by the API, provide a request body, and set a content type. The exact endpoints and validation rules come from that service's documentation; do not assume every server uses the same route. This example demonstrates the browser mechanics with a generic course progress endpoint.
async function saveProgress(courseId, completedLessonIds) {
const response = await fetch('/api/course-progress', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({ courseId, completedLessonIds }),
})
if (!response.ok) {
throw new Error('Progress could not be saved')
}
return response.json()
}
saveProgress('javascript', ['javascript-fundamentals'])
.then((result) => console.log('Saved', result))
.catch((error) => console.error(error.message))Browser requests may also need authentication, cross-origin configuration, or CSRF protection depending on the application. Those are server and deployment design concerns, not a reason to put private credentials in client code. Check the API contract and security model before sending personal data.
Stop Work That Is No Longer Needed
A search can become outdated while a user types a newer query. AbortController lets code cancel a fetch that is no longer useful. Cancellation is not the same as a normal server error; it is often an expected outcome when a user navigates away or replaces a request.
let activeController
async function searchCourses(query) {
activeController?.abort()
activeController = new AbortController()
const signal = activeController.signal
try {
const response = await fetch(
'/api/courses?search=' + encodeURIComponent(query),
{ signal },
)
if (!response.ok) throw new Error('Search failed')
return await response.json()
} catch (error) {
if (error.name === 'AbortError') return null
throw error
}
}Debouncing can reduce how often a search request starts while a person is typing. Aborting an old request prevents wasted work and stale results from winning a race. If the operation has important side effects, cancellation in the browser does not guarantee the server did not already process it.
A timeout can be implemented with an abort signal where supported by your target runtime, or with a controller and timer. Always clear timers when a request finishes. Avoid writing a homemade retry loop before you know which failures are transient and whether repeating the operation is safe.
Common Mistakes
Assuming fetch rejects on a 404 or 500
Why: fetch usually resolves with a Response for HTTP error statuses.
Fix: Check response.ok or status and throw an error for unsuccessful responses.
Forgetting to await response.json()
Why: Reading and parsing the response body returns a promise.
Fix: Await the body reader and handle parsing failures as part of the request flow.
Showing a blank page while waiting
Why: The request has no visible loading state and gives no completion feedback.
Fix: Represent loading, success, empty, and error states explicitly.
Using returned text as HTML
Why: A response may contain untrusted content that can execute as markup.
Fix: Validate the payload and render text with textContent or a safe component.
Build a Course Search Request
Practice
Load a remote list and keep the interface honest
- Write a Promise-based helper and then rewrite its caller using async and await.
- Fetch a course list and handle a non-OK response before parsing JSON.
- Add loading, empty, error, and success messages to a small page.
- Validate that the response is an array and that each course has a string title before rendering.
- Send a JSON progress update with the appropriate method and content type.
- Cancel an outdated search when a newer query starts; distinguish abort from a genuine failure.
Hint: Use a live status message and textContent for rendered titles; do not infer success from the absence of an exception.
🎯 Key Takeaways
- ✓Asynchronous work lets the browser remain responsive while timers or network requests are pending.
- ✓A promise represents a future fulfillment or rejection; return promises to keep chains connected.
- ✓async functions return promises, and await makes their steps easier to read without blocking the page.
- ✓fetch does not reject just because an HTTP status is unsuccessful; check response.ok.
- ✓Reading JSON is asynchronous, and external response data should be validated before use.
- ✓Give users explicit loading, success, empty, and error states, and use safe DOM rendering.
- ✓Abort obsolete requests and retry only when the operation and failure make retry safe.
Next
What comes next
You can fetch and handle remote data. Next, split code into modules and use npm and Vite to organize an application.
Lesson 10 · Modules, npm and Build Tooling →HELP US IMPROVE
How was this lesson?
Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.
Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.
