fundamentals

Promise Fundamentals in TypeScript

What is a Promise?

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It provides a cleaner alternative to callbacks for handling async code.

Promise States

  • Pending: Initial state, operation in progress
  • Fulfilled: Operation completed successfully with a value
  • Rejected: Operation failed with an error

Basic Syntax

const promise: Promise<T> = new Promise((resolve, reject) => {
  // Async operation
  if (success) {
    resolve(value); // Type T
  } else {
    reject(error);
  }
});

Type Annotations

// Promise with string result
const getName: Promise<string> = Promise.resolve("Alice");

// Promise with number result
const getAge: Promise<number> = new Promise((resolve) => {
  setTimeout(() => resolve(25), 1000);
});

// Promise that may reject
const riskyOperation: Promise<number> = new Promise((resolve, reject) => {
  Math.random() > 0.5 ? resolve(42) : reject(new Error("Failed"));
});

Consuming Promises

Using .then() and .catch()

promise
  .then((result: T) => {
    console.log(result);
    return processedValue; // Can chain
  })
  .catch((error: Error) => {
    console.error(error);
  })
  .finally(() => {
    // Cleanup code
  });

Using async/await

async function handlePromise(): Promise<void> {
  try {
    const result: T = await promise;
    console.log(result);
  } catch (error) {
    console.error(error);
  }
}

Utility Methods

// Wait for all promises
const results: [string, number] = await Promise.all([
  Promise.resolve("hello"),
  Promise.resolve(42)
]);

// Race between promises
const first: string | number = await Promise.race([
  fetchFromAPI1(),
  fetchFromAPI2()
]);

// Wait for all to settle (success or failure)
const outcomes = await Promise.allSettled([promise1, promise2]);

// First fulfilled promise (ignores rejections)
const firstSuccess = await Promise.any([promise1, promise2]);

Generic Type Inference

TypeScript automatically infers Promise types in many cases:

async function fetchUser(id: number): Promise<User> {
  const response = await fetch(`/api/users/${id}`);
  return response.json(); // Return type inferred as User
}

// Type of userData is User
const userData = await fetchUser(123);

Common Patterns

// Promisifying callbacks
function delay(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// Error handling with type guards
async function safeOperation(): Promise<Result | null> {
  try {
    return await riskyOperation();
  } catch (error) {
    if (error instanceof NetworkError) {
      // Handle specific error
    }
    return null;
  }
}

Backlinks