Reference Guide

Table of Contents

  1. Asynchronous JavaScript Fundamentals

  2. Callbacks

  3. Promises

  4. Async/Await

  5. Fetch API

  6. AJAX & HTTP

  7. Working with JSON

  8. Practical Patterns

  9. Best Practices

  10. Common Mistakes


1. Asynchronous JavaScript Fundamentals

Synchronous vs Asynchronous

Synchronous: Code executes line by line, one at a time

console.log('First');
console.log('Second');
console.log('Third');
// Output: First, Second, Third (in order)

Asynchronous: Code can start tasks and continue without waiting

The Event Loop

Components:

  • Call Stack - Where code executes

  • Web APIs - Browser features (setTimeout, fetch, etc.)

  • Callback Queue - Completed async tasks wait here

  • Event Loop - Moves tasks from queue to stack when stack is empty

Key Concept: Even setTimeout(fn, 0) is asynchronous!

Common Async Operations

  • Timers: setTimeout(), setInterval()

  • Network requests: fetch(), AJAX calls

  • User events: addEventListener()

  • File operations (Node.js)


2. Callbacks

What is a Callback?

A function passed as an argument to another function, executed later.

Async Callbacks

Error-First Callback Pattern (Node.js)

Callback Hell

Problem: Nested callbacks become hard to read

Solution: Use Promises or async/await (covered next)


3. Promises

What is a Promise?

A Promise represents a value that may be available now, in the future, or never.

Promise States:

  • Pending - Initial state, operation in progress

  • Fulfilled - Operation completed successfully

  • Rejected - Operation failed

Creating a Promise

Example with Timeout

Consuming Promises

Using .then() and .catch()

Promise Chaining

Promise Static Methods

Promise.all() - All must succeed

Promise.allSettled() - Wait for all

Promise.race() - First to finish

Promise.any() - First to succeed

Comparison Table:

Method
Returns
Rejects When

Promise.all()

All results

Any fails

Promise.allSettled()

All results

Never

Promise.race()

First settled

First rejection

Promise.any()

First success

All fail


4. Async/Await

The Modern Way to Handle Async Code

Async/await makes asynchronous code look synchronous.

The async Keyword

The await Keyword

Rules:

  • Can ONLY use await inside async functions

  • await pauses execution until Promise resolves

  • Returns the resolved value

Error Handling with Try/Catch

Parallel vs Sequential

❌ Sequential (Slow) - 3 seconds total

✅ Parallel (Fast) - 1 second total

Converting Promises to Async/Await

Promises:

Async/Await:


5. Fetch API

Basic Syntax

With async/await (Recommended):

GET Request

POST Request

PUT Request (Update)

PATCH Request (Partial Update)

DELETE Request

Response Object

Important Properties:

Response Methods:

Request Headers

Fetch Options

Aborting Requests

CRITICAL: Fetch Doesn't Reject on HTTP Errors!


6. AJAX & HTTP

What is AJAX?

AJAX = Asynchronous JavaScript and XML (Despite the name, we use JSON now, not XML)

Technique for:

  • Updating parts of a page without reloading

  • Requesting data from servers asynchronously

  • Sending data to servers in the background

HTTP Request/Response Cycle

Request Parts:

  1. Method - GET, POST, PUT, DELETE, etc.

  2. URL - Resource path

  3. Headers - Metadata (Content-Type, Authorization)

  4. Body - Data being sent (optional)

Response Parts:

  1. Status Code - 200, 404, 500, etc.

  2. Headers - Response metadata

  3. Body - Response data

HTTP Status Codes

2xx - Success

  • 200 OK - Request succeeded

  • 201 Created - Resource created

  • 204 No Content - Success, no response body

4xx - Client Error

  • 400 Bad Request - Invalid request

  • 401 Unauthorized - Authentication required

  • 403 Forbidden - Access denied

  • 404 Not Found - Resource doesn't exist

5xx - Server Error

  • 500 Internal Server Error - Server crashed

  • 503 Service Unavailable - Server overloaded

HTTP Methods (CRUD)

Operation
Method
Purpose

Create

POST

Create new resource

Read

GET

Retrieve resource

Update (full)

PUT

Replace entire resource

Update (partial)

PATCH

Modify resource

Delete

DELETE

Remove resource

RESTful API Conventions

URL Patterns:

Query Parameters:

Best Practices:

  • Use nouns for resources (/users not /getUsers)

  • Use HTTP methods for actions

  • Use plural nouns (/users not /user)

  • Be consistent

  • Version your API (/api/v1/users)


7. Working with JSON

JSON Syntax

Rules:

  • Property names in double quotes

  • String values in double quotes

  • No trailing commas

  • No comments

  • No functions

JSON vs JavaScript Object

JSON.stringify() - Object to JSON String

JSON.parse() - JSON String to Object

JSON with Fetch

Important: JSON Limitations


8. Practical Patterns

Complete API Request Pattern

Loading States

Debouncing (Search Input)

Retry Logic

Caching

Error Handling by Status Code


9. Best Practices

1. Always Handle Errors

2. Check response.ok

3. Use JSON.stringify() for POST/PUT

4. Set Content-Type Header

5. Show Loading States

6. Use Promise.all() for Parallel Requests

7. Debounce Search Inputs

8. Never Expose API Keys in Frontend

9. Validate User Input

10. Use Appropriate HTTP Methods


10. Common Mistakes

1. Forgetting await

2. Not Checking response.ok

3. Forgetting JSON.stringify()

4. Sequential Instead of Parallel

5. Not Handling Errors

6. Using .then() with async/await

7. Not Disabling Buttons During Requests


Quick Reference

Fetch Template

CRUD Operations

Promise Methods


Practice APIs

Free APIs for Testing:

  • JSONPlaceholder - https://jsonplaceholder.typicode.com/

  • Dog API - https://dog.ceo/dog-api/

  • Pokemon API - https://pokeapi.co/

  • GitHub API - https://api.github.com/

  • Open Weather - https://openweathermap.org/api

Last updated