Managing Asynchronous Operations with Promises

Discover how to use Promises in TypeScript to handle asynchronous tasks, ensuring clean and maintainable code for async operations.

Managing Asynchronous Operations with Promises
Photo by Roman Synkevych / Unsplash

Discover how to use Promises in TypeScript to handle asynchronous tasks, ensuring clean and maintainable code for async operations.

function fetchData(): Promise<string> {
  return new Promise((resolve, reject) => {
    // Simulate fetching data
    setTimeout(() => {
      resolve("Data fetched successfully");
    }, 1000);
  });
}

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