Understanding Promises and Subscriptions in Angular: A Comprehensive Guide

Alice
3 min readSep 29, 2023

--

In Angular interviews, one of the most common questions is about the differences between Promises and Subscriptions and which one to use in different situations.

In this article, we’ll explore these two commonly used ways of handling asynchronous data: Promises and Observables with Subscriptions. Their differences and code examples will be provided to help you understand their usage.

Promises in Angular

Promises are a fundamental part of JavaScript, and Angular leverages them to handle asynchronous operations. A Promise represents a single value that may not be available yet but will be resolved or rejected in the future. Promises have three main states:

  1. Pending: The initial state where the promise is neither resolved nor rejected.
  2. Fulfilled (Resolved): The state where the promise successfully resolves, and a value is available.
  3. Rejected: The state where the promise fails to resolve, and an error is encountered.

Here’s a basic example of using Promises in Angular:

function fetchData() {

return new Promise((resolve, reject) => {
// Simulate an asynchronous operation
setTimeout(() => {
const data = { message: "Data fetched successfully" };
resolve(data); // Resolve the promise with the data
}, 2000);
});
}

fetchData()
.then((data) => {
console.log(data.message); // Output: Data fetched successfully
})
.catch((error) => {
console.error("Error:", error);
});

In this example, we define a function fetchData that returns a Promise. We use resolve to fulfill the promise when the data is available and reject to reject it in case of an error.

Subscriptions with Observables in Angular

Angular uses Observables to handle asynchronous data streams. Observables are more versatile than Promises because they can emit multiple values over time, making them suitable for handling events, HTTP requests, and more. To consume data from an Observable, you need to subscribe to it.

Here’s an example of using Observables and Subscriptions in Angular:

import { Observable } from 'rxjs';

function fetchDataObservable() {
return new Observable((observer) => {
// Simulate an asynchronous operation
setTimeout(() => {
const data = { message: "Data fetched using Observable" };
observer.next(data); // Emit a value
observer.complete(); // Complete the observable
}, 2000);
});
}

const subscription = fetchDataObservable().subscribe({
next: (data) => {
console.log(data.message); // Output: Data fetched using Observable
},
error: (error) => {
console.error("Error:", error);
},
complete: () => {
console.log("Observable complete");
},
});

// Later, you can unsubscribe to release resources
subscription.unsubscribe();

In this example, we define an Observable using the Observable class from the 'rxjs' library. We use observer.next() to emit a value and observer.complete() to indicate the Observable has finished emitting values. To consume the data, we subscribe to the Observable, and when done, we unsubscribe to prevent memory leaks.

Key Differences

Now, let’s summarize the key differences between Promises and Subscriptions in Angular:

  1. Single Value vs. Multiple Values: Promises resolve to a single value or reject with an error, while Observables can emit multiple values over time.
  2. Eager vs. Lazy: Promises are eager, meaning they start executing as soon as they are created. Observables are lazy, so they don’t start until someone subscribes to them.
  3. Cancellation: Promises cannot be canceled once they start executing, whereas Observables can be unsubscribed to stop further emissions and prevent memory leaks.
  4. Built-in vs. Library: Promises are built into JavaScript, while Observables are part of the ‘rxjs’ library that needs to be imported and managed in your Angular application.

Conclusion

Promises and Subscriptions with Observables are both valuable tools for handling asynchronous operations in Angular. Promises are suitable for scenarios where you expect a single result, while Observables with Subscriptions provide more flexibility, making them ideal for handling data streams and events. Understanding when to use each of these mechanisms is crucial for building efficient and responsive Angular applications.

--

--