Difference between promise and observable


Promises and Observables are both used to handle asynchronous operations in JavaScript, but they have key differences in how they work and their capabilities. Here’s a breakdown:



Promises

Definition: A Promise represents a single future value or the eventual completion (or failure) of an asynchronous operation.

Execution: A Promise is eager, meaning it executes immediately when created.

Value Handling: A Promise can only handle a single value or error. Once resolved or rejected, it cannot emit multiple values.

Chaining: You can chain .then() and .catch() methods to handle the resolved value or error.

Cancellation: Promises cannot be canceled once they are initiated.

Use Case: Ideal for one-time asynchronous operations like fetching data from an API.

const promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Data fetched!"), 1000);
});

promise.then((result) => console.log(result)); // Output: "Data fetched!"
Enter fullscreen mode

Exit fullscreen mode



Observables

Definition: An Observable represents a stream of values over time. It can emit multiple values, errors, or a completion signal.

Execution: Observables are lazy, meaning they only execute when you subscribe to them.

Value Handling: Observables can emit multiple values over time, making them suitable for handling streams of data (e.g., user input, WebSocket messages).

Chaining: You can use operators like map, filter, and merge to transform or combine streams.

Cancellation: Observables can be canceled using the unsubscribe() method, which stops the stream.

Use Case: Ideal for handling continuous or multiple asynchronous events, such as real-time data streams or user interactions.

import { Observable } from 'rxjs';

const observable = new Observable((subscriber) => {
  subscriber.next("First value");
  setTimeout(() => subscriber.next("Second value"), 1000);
  setTimeout(() => subscriber.complete(), 2000);
});

const subscription = observable.subscribe({
  next: (value) => console.log(value), // Output: "First value", then "Second value"
  complete: () => console.log("Completed!"),
});

subscription.unsubscribe(); // Cancel the subscription
Enter fullscreen mode

Exit fullscreen mode



When to Use Which?

  • Use a Promise when you need to handle a single asynchronous operation (e.g., fetching data from an API).
  • Use an Observable when dealing with multiple values over time or continuous streams of data (e.g., real-time updates, user input events).

Observables are more powerful and flexible, but Promises are simpler and sufficient for many use cases.



Source link