theory.ts

Asynchronous

Callbacks and Promises

Promises provide a cleaner alternative to callbacks for handling asynchronous operations.

  • A callback function is passed to another function and executed later.
  • A promise represents a future value and supports `.then()` chaining.
  • Promises prevent callback nesting issues ('callback hell').
// Callback-based approach
function fetchData(callback: (data: string) => void): void {
  setTimeout(() => {
    callback("Data received");
  }, 2000);
}

fetchData((data) => {
  console.log(data);
});

// Promise-based approach
function fetchData(): Promise<string> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Data received");
    }, 2000);
  });
}

fetchData().then((data) => console.log(data));