Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Module 12: Promises & API Interaction

1. What is a Promise?

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. Think of it as a “placeholder” for a value that hasn’t arrived yet.

The 3 States of a Promise:

  1. Pending: Initial state, neither fulfilled nor rejected.
  2. Fulfilled (Resolved): The operation completed successfully.
  3. Rejected: The operation failed (e.g., network error).

2. Consuming Promises (.then, .catch, .finally)

When a promise is returned (like from a network request), we use handlers to deal with the result.

JavaScript

const myPromise = new Promise((resolve, reject) => {
    let success = true;
    if (success) {
        resolve("Data received!");
    } else {
        reject("Error: Connection lost.");
    }
});

myPromise
    .then((data) => console.log(data))    // Runs if Resolved
    .catch((err) => console.error(err))   // Runs if Rejected
    .finally(() => console.log("Done"));  // Runs always

3. The Fetch API

fetch() is the modern way to make HTTP requests (API calls). It returns a Promise.

Crucial Note: A fetch() promise only rejects if there is a network error. It does not reject for 404 or 500 errors. You must check the response.ok property.

JavaScript

fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => {
        if (!response.ok) throw new Error("HTTP error " + response.status);
        return response.json(); // .json() also returns a promise!
    })
    .then(data => console.log(data))
    .catch(error => console.error("Request Failed:", error));

4. Chaining Promises

One of the best features of Promises is that you can chain them. Each .then() returns a new promise, allowing you to process data in steps.

JavaScript

getUser(1)
    .then(user => getPosts(user.id))
    .then(posts => getComments(posts[0].id))
    .then(comments => console.log(comments))
    .catch(err => console.log(err)); // One catch for the whole chain!

5. Handling Multiple Promises

Sometimes you need to trigger multiple requests at once. JavaScript provides static methods for this:

MethodBehavior
Promise.all([p1, p2])Waits for all to succeed. If one fails, the whole thing fails immediately.
Promise.allSettled([p1, p2])Waits for all to finish, regardless of success or failure. Returns an array of results.
Promise.race([p1, p2])Returns the result of the first promise to settle (fastest one wins).
Promise.any([p1, p2])Returns the first successful promise. If all fail, it throws an error.

6. Avoiding “Callback Hell”

Before promises, we had nested functions inside functions. Promises flatten this structure, making the code much more readable.


Technical Code Example: The Parallel Fetch

Let’s say you want to get a User and their Posts at the same time to save time.

JavaScript

const userReq = fetch('https://api.example.com/user/1');
const postReq = fetch('https://api.example.com/user/1/posts');

Promise.all([userReq, postReq])
    .then(responses => {
        // Convert both responses to JSON
        return Promise.all(responses.map(res => res.json()));
    })
    .then(([userData, postData]) => {
        console.log("User:", userData);
        console.log("Posts:", postData);
    })
    .catch(err => console.error("One of the requests failed", err));

In Simple words

1. Why Promises Matter

Modern applications constantly:

  • Fetch data from servers
  • Communicate with microservices
  • Handle async workflows
  • Manage failures gracefully

Promises provide a clean, predictable, and composable way to handle async code.


2. The Problem with Callbacks

Callback Hell

  • Nested functions
  • Hard to read & debug
  • Poor error handling

Promises solve:

  • Inversion of control
  • Error propagation
  • Readability

3. What Is a Promise?

Definition

A Promise is an object that represents:

The eventual completion or failure of an asynchronous operation.


4. Promise States

StateMeaning
PendingInitial state
FulfilledResolved successfully
RejectedFailed

A promise is settled once fulfilled or rejected.


5. Creating Promises

  • Executor function
  • resolve and reject
  • Single settlement rule

6. Consuming Promises

.then()

  • Handles fulfillment
  • Chainable

.catch()

  • Handles rejection

.finally()

  • Cleanup logic

7. Promise Chaining

  • Return values auto-wrapped into promises
  • Enables sequential async flow
  • Errors propagate downstream

8. Async / Await Deep Dive

  • Syntactic sugar over promises
  • Looks synchronous
  • Uses microtask queue internally

9. Error Handling Strategies

  • Try/catch with async/await
  • Centralized error handlers
  • Graceful degradation

10. Promise Combinators

Promise.all

  • Runs in parallel
  • Fails fast

Promise.allSettled

  • Waits for all results
  • No short-circuit

Promise.race

  • First settled wins

Promise.any

  • First fulfilled wins

11. Parallel vs Sequential Execution

PatternUse Case
SequentialDependent calls
ParallelIndependent APIs

12. API Interaction Basics

What Is an API?

  • Application Programming Interface
  • Communication contract between systems

13. HTTP Fundamentals

  • Methods: GET, POST, PUT, PATCH, DELETE
  • Status codes:
    • 2xx Success
    • 4xx Client errors
    • 5xx Server errors

14. Fetching Data

Fetch API

  • Promise-based
  • Returns Response object
  • Requires manual JSON parsing

15. Request & Response Lifecycle

  1. Client request
  2. DNS lookup
  3. TCP handshake
  4. Server processing
  5. Response parsing

16. Headers & Payloads

  • Content-Type
  • Authorization
  • JSON vs FormData

17. Authentication in APIs

  • API keys
  • Tokens (JWT)
  • OAuth (intro)

18. Handling API Errors

  • Network errors
  • Timeout
  • Non-200 responses
  • JSON parsing failures

19. Retry & Timeout Patterns

  • Exponential backoff
  • Circuit breakers
  • AbortController

20. Caching API Responses

  • Browser cache
  • In-memory cache
  • CDN caching
  • Stale-while-revalidate

21. Security Best Practices

  • HTTPS only
  • Never expose secrets
  • CORS understanding
  • Input validation

22. Rate Limiting & Throttling

  • Prevent abuse
  • Improve stability
  • Client-side vs server-side

23. Pagination & Infinite Scroll

  • Offset-based
  • Cursor-based
  • Performance considerations

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥