Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Promises

A Promise represents the eventual completion or failure of an asynchronous operation. It allows us to handle results that may become available later, such as API responses, database-related requests, or file operations.

Learning objective: Understand Promise states, create a Promise, handle success and failure, chain asynchronous operations, and execute multiple Promises together.

1. What Is a Promise?

A Promise is a JavaScript object that represents the future result of an operation. The result may be successful or unsuccessful. TypeScript uses JavaScript's built-in Promise API and provides types such as Promise<string> and Promise<number>.

⏳
Pending

The asynchronous operation has not settled yet.

✅
Fulfilled

The operation completed successfully.

❌
Rejected

The operation failed with a rejection reason.

Remember: A Promise starts in the pending state and settles as fulfilled or rejected. Once settled, it cannot change to the other state.

2. Why Do We Need Promises?

Many operations do not finish immediately. For example, an application may request student information from a server. Promises let the program register handlers for the eventual result instead of blocking while the request completes.

🌐
API Requests

Handle data returned from a server.

📦
Data Processing

Manage results from asynchronous tasks.

⚠️
Error Handling

Handle rejected operations with clear error paths.

🔗
Task Chaining

Run dependent operations in sequence.

3. Promise Syntax

Use the Promise constructor to create a Promise. Its executor function receives two callbacks: resolve for successful completion and reject for failure.

const resultPromise: Promise<string> = new Promise(
    (resolve, reject) => {
        const success = true;

        if (success) {
            resolve("Operation completed successfully");
        } else {
            reject(new Error("Operation failed"));
        }
    }
);

Important Parts

  • Promise<string> indicates that the fulfilled value is a string.
  • resolve() fulfills the Promise with a value.
  • reject() rejects the Promise with a reason, often an Error.
  • The executor function runs synchronously when the Promise is created.

4. Create and Use a Simple Promise

In this example, a Promise returns a student name. The then() method handles the fulfilled value.

const studentPromise: Promise<string> = new Promise(
    (resolve) => {
        resolve("Rahul");
    }
);

studentPromise.then((studentName: string) => {
    console.log("Student Name: " + studentName);
});

Expected Output

Student Name: Rahul

Execution Flow

📝
Create Promise

Initialize the operation

→
✅
Resolve

Return the value Rahul

→
📤
then()

Handle and display the result

5. then(), catch(), and finally()

These methods are commonly used to handle the result and cleanup steps of a Promise-based operation.

Method Purpose When It Runs
then() Handles fulfillment, and can also handle rejection when given a second callback. According to the Promise's settled result.
catch() Handles a rejection or an error propagated through the chain. When the preceding Promise rejects or a handler throws.
finally() Runs cleanup logic without receiving the fulfillment value or rejection reason as an argument. After the Promise settles, whether fulfilled or rejected.

Example

const marksPromise: Promise<number> = new Promise(
    (resolve, reject) => {
        const marks = 85;

        if (marks >= 40) {
            resolve(marks);
        } else {
            reject(new Error("Student failed"));
        }
    }
);

marksPromise
    .then((marks) => {
        console.log("Marks: " + marks);
        console.log("Result: Pass");
    })
    .catch((error: Error) => {
        console.log("Error: " + error.message);
    })
    .finally(() => {
        console.log("Result processing completed");
    });

Expected Output

Marks: 85
Result: Pass
Result processing completed
Note: finally() is useful for cleanup tasks such as hiding a loading indicator. If the callback throws an error or returns a rejected Promise, the Promise returned by finally() can reject.

6. Handling a Rejected Promise

If an operation fails, call reject() or throw an error from the Promise executor. A following catch() can handle that rejection.

const paymentPromise: Promise<string> = new Promise(
    (resolve, reject) => {
        const paymentSuccessful = false;

        if (paymentSuccessful) {
            resolve("Payment completed");
        } else {
            reject(new Error("Payment failed"));
        }
    }
);

paymentPromise
    .then((message) => {
        console.log(message);
    })
    .catch((error: Error) => {
        console.log("Error: " + error.message);
    });

Expected Output

Error: Payment failed
Best practice: Reject with an Error object when reporting an error. It provides a meaningful message and works well with standard error handling.

7. Promise Chaining

Promise chaining lets one asynchronous step depend on the result of an earlier step. When a then() callback returns a value, the next step receives that value. When it returns a Promise, the chain waits for that Promise to settle.

Promise.resolve(10)
    .then((value) => {
        console.log("Initial Value: " + value);
        return value + 5;
    })
    .then((value) => {
        console.log("After Addition: " + value);
        return value * 2;
    })
    .then((value) => {
        console.log("Final Value: " + value);
    })
    .catch((error: Error) => {
        console.log(error.message);
    });

Expected Output

Initial Value: 10
After Addition: 15
Final Value: 30

Chaining Flow

🔢
Initial Value

10

→
➕
Add 5

15

→
✖️
Multiply by 2

30

8. Promise.all()

Promise.all() accepts an iterable of Promises and fulfills when all of them fulfill. It returns the results in the same order as the input Promises. If any input rejects, the returned Promise rejects.

const studentPromise = Promise.resolve("Rahul");
const coursePromise = Promise.resolve("TypeScript");
const marksPromise = Promise.resolve(90);

Promise.all([
    studentPromise,
    coursePromise,
    marksPromise
]).then(([student, course, marks]) => {
    console.log("Student: " + student);
    console.log("Course: " + course);
    console.log("Marks: " + marks);
}).catch((error: Error) => {
    console.log("Error: " + error.message);
});

Expected Output

Student: Rahul
Course: TypeScript
Marks: 90
Use case: When a page requires multiple independent responses, such as student details, course details, and marks, Promise.all() can coordinate them together.

9. Promise.race()

Promise.race() settles according to the first input Promise that settles. That first result may be fulfilled or rejected.

const firstPromise = new Promise<string>((resolve) => {
    setTimeout(() => resolve("First operation completed"), 1000);
});

const secondPromise = new Promise<string>((resolve) => {
    setTimeout(() => resolve("Second operation completed"), 2000);
});

Promise.race([firstPromise, secondPromise])
    .then((result) => {
        console.log(result);
    })
    .catch((error: Error) => {
        console.log(error.message);
    });

Expected Output

First operation completed
Important: The example assumes both timers run normally and the first timer settles first. Promise.race() does not automatically cancel the losing operation.

10. Promise.allSettled()

Promise.allSettled() waits until every input Promise has settled, whether fulfilled or rejected. It returns an array containing each operation's status and result or rejection reason.

const taskOne = Promise.resolve("Task one completed");
const taskTwo = Promise.reject(new Error("Task two failed"));

Promise.allSettled([taskOne, taskTwo])
    .then((results) => {
        results.forEach((result, index) => {
            if (result.status === "fulfilled") {
                console.log("Task " + (index + 1) + ": " + result.value);
            } else {
                console.log(
                    "Task " + (index + 1) + ": " + result.reason.message
                );
            }
        });
    });

Expected Output

Task 1: Task one completed
Task 2: Task two failed

Unlike Promise.all(), one rejection does not cause Promise.allSettled() to reject because of that input. It waits for all of the input Promises to settle.

11. Callback vs Promise

Feature Callback Promise
Basic idea A function passed to another function An object representing a future result
Chaining May require nested callbacks Supports chains using then()
Error handling Depends on the callback design Supports rejection handlers such as catch()
Async/await Not directly awaitable unless wrapped or converted Can be awaited directly
Remember: Promises do not make every operation asynchronous by themselves. They provide a standard way to represent and handle operations that may complete later.

12. Common Mistakes

Forgetting to return

When chaining operations, return the next value or Promise if the following step depends on it.

Missing error handling

Add appropriate rejection handling with catch() or use try/catch with async/await.

Assuming Promise.all ignores errors

If any input rejects, Promise.all() rejects. Use Promise.allSettled() when each outcome is needed.

Forgetting Promise type

Specify a suitable result type, such as Promise<number>, to improve TypeScript type checking.

Summary

  • A Promise represents the eventual result of an asynchronous operation.
  • Its states are pending, fulfilled, and rejected.
  • then() handles results, catch() handles rejection, and finally() runs cleanup logic.
  • Promise chaining connects dependent operations.
  • Promise.all() fulfills when all inputs fulfill and rejects if one rejects.
  • Promise.race() follows the first settled input.
  • Promise.allSettled() reports the outcome of every input.
  • async/await provides another readable way to work with Promises.