Skip to content

Callbacks vs Promises

Two ways to handle async code. Callbacks came first, Promises are cleaner.

Pass a function to run when the async work is done:

function fetchData(callback: (data: string) => void): void {
  setTimeout(() => {
    callback("Here is your data");
  }, 1000);
}

fetchData((result) => {
  console.log(result); // "Here is your data" after 1 second
});

Returns an object you can chain with .then():

function fetchData(): Promise<string> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Here is your data");
    }, 1000);
  });
}

fetchData().then((result) => {
  console.log(result);
});

Syntactic sugar over Promises - looks like sync code:

async function getData(): Promise<void> {
  const result = await fetchData();
  console.log(result);
}