Promises in Angular

πŸš€ Promises in Angular – The Complete Beginner’s Guide (with Examples)

πŸ“˜ Introduction

In modern Angular development, handling asynchronous operations is essential. Whether you're fetching data from an API, loading files, or wrapping browser-native APIs, Promises offer a clean and readable way to deal with one-time asynchronous operations.

This guide explains:

  • What Promises are
  • How they compare with Observables
  • Real-world examples using .then() and async/await
  • When to use Promises vs Observables in Angular

πŸ“š Table of Contents

πŸ” What is a Promise?

A Promise is a JavaScript object that represents the eventual success (fulfilled) or failure (rejected) of an asynchronous operation.

πŸ“Œ Common use cases in Angular:

  • ✅ One-time data fetches
  • ✅ Wrapping browser APIs (e.g., Geolocation)
  • ✅ Simple async service logic

✨ Key Features of Promises

Start → Promise Created (Pending)
         ↓
     Resolve (Fulfilled) → .then()
         ↓
     Reject (Error)     → .catch()

✨ Key Features of Promises

  • ✅ Single resolution – A Promise resolves once via resolve() or reject()
  • ⏱ Eager execution – Promises begin execution as soon as created
  • 🚫 Not cancelable – Once started, runs to completion
  • 🧠 Great with async/await – Improves code readability

🧾 Promise Syntax


myPromise
  .then(response => console.log("Success:", response))
  .catch(error => console.error("Error:", error))
  .finally(() => console.log("Completed"));

πŸ’» Example 1: Fetch Data Using fetch()

While Angular’s HttpClient returns Observables, you can use native fetch() to work with Promises directly.


function fetchData(): Promise<string> {
  return fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then(response => {
      if (!response.ok) throw new Error("Network response was not ok");
      return response.json();
    })
    .then(data => `Title: ${data.title}`);
}

// ✅ Using .then()
function usingThen() {
  fetchData()
    .then(result => console.log("Using .then():", result))
    .catch(error => console.error("Error:", error));
}

// ✅ Using async/await
async function usingAsyncAwait() {
  try {
    const result = await fetchData();
    console.log("Using async/await:", result);
  } catch (error) {
    console.error("Error:", error);
  }
}

πŸ§ͺ Output:

  • Using .then(): Title: sunt aut facere repellat provident occaecati
  • Using async/await: Title: sunt aut facere repellat provident occaecati

πŸ’» Example 2: Simulate Async Operation with setTimeout


function fetchData(): Promise<string> {
  return new Promise((resolve) => {
    setTimeout(() => resolve("Data loaded"), 1000);
  });
}

function usingThen() {
  fetchData().then(result => console.log("Using .then():", result));
}

async function usingAsyncAwait() {
  try {
    const result = await fetchData();
    console.log("Using async/await:", result);
  } catch (error) {
    console.error("Error:", error);
  }
}

usingThen();
usingAsyncAwait();

πŸ§ͺ Output:

  • Using .then(): Data loaded
  • Using async/await: Data loaded

πŸ“Š Promises vs Observables in Angular

Feature Promise Observable
Emits multiple values
Lazy execution
Cancelable
Built-in operators (map etc) ✅ (RxJS)
Best for... ✅ One-time tasks ✅ Streams/data flows

🎯 When Should You Use Promises?

  • ✅ You need one-time async operations
  • ✅ You work with browser-native APIs
  • ✅ You prefer using async/await
  • ✅ Simpler logic flow is sufficient

πŸ“¦ Real Angular Example: Service Returning a Promise


@Injectable({ providedIn: 'root' })
export class DataService {
  getData(): Promise<string> {
    return new Promise((resolve) => {
      setTimeout(() => resolve("Data from service"), 1000);
    });
  }
}

// In Component:
constructor(private dataService: DataService) {}

ngOnInit() {
  this.dataService.getData().then(data => console.log(data));
}

πŸ”„ Observable vs Promise with Angular HttpClient

✅ Using Observable (default):


this.http.get('url').subscribe(response => console.log(response));

πŸ” Convert to Promise:


this.http.get('url').toPromise().then(response => console.log(response));

⚠️ Note: As of Angular v16+, toPromise() is deprecated. Use lastValueFrom() from RxJS instead.

❓ Frequently Asked Questions

  1. Can Promises be cancelled?
    No, once a Promise starts it cannot be cancelled.
  2. When should I use Promises in Angular?
    For one-time operations like API calls or using browser APIs.
  3. Are Promises better than Observables?
    Promises are simpler for one-off tasks, while Observables handle streams and reactive data better.
  4. Should I use async/await or .then()?
    Use async/await for cleaner, more readable code.

✅ Summary

  • Promises simplify one-time asynchronous operations in Angular.
  • Use .then(), .catch(), .finally() or async/await for better flow.
  • Prefer Observables for streams, multiple values, and Angular HttpClient.
  • Visualizing the Promise lifecycle helps understand its behavior.
  • Choose the right tool—Promise or Observable—based on your specific use case.

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features