Exploring the Distinctions: Promise Vs Observable
In the realm of JavaScript/TypeScript programming, Promise and Observable are two central concepts that aid in handling asynchronous operations. These concepts, while seeming similar, possess distinctive characteristics and functionalities.
Promises: One-Time Guarantee
Promises are objects in JavaScript that link the ‘producing code’ and the ‘consuming code’ together, which means they connect the code that will execute a certain action and the code that will respond to the outcome of that action.
Promises can only be resolved (fulfilled or rejected) once. In simpler terms, it represents a single eventual value from an asynchronous operation. A Promise can be in one of three states:
- Pending: The Promise’s outcome hasn’t yet been determined.
- Fulfilled: The action relating to the Promise succeeded.
- Rejected: The action relating to the Promise failed.
Once a Promise is settled (either fulfilled or rejected), it becomes immutable, meaning its state cannot be changed. Promises are commonly used with the .then method to handle the outcome, whether it is a success (resolve) or an error (reject).
function examplePromise(): Promise<string> { return new Promise((resolve, reject) => { setTimeout(() => { resolve("Promise resolved!"); // After 2 seconds, the Promise will resolve }, 2000); }); } examplePromise().then(result => { console.log(result); // Logs "Promise resolved!" after 2 seconds }).catch(error => { console.log(error); });
In this example, we have a function examplePromise that returns a Promise. The Promise resolves after 2 seconds, then we handle the resolved value with .then.
Observables: Stream of Information
Unlike Promises, Observables deal with a sequence or stream of values over time, rather than just a one-time event. They are part of the RxJS library and are inspired by the observer pattern, the iterator pattern, and functional programming.
An Observable sequence can emit zero or more values, and it can either complete successfully or result in an error. Moreover, Observables are lazy, which means they are not executed until a consumer subscribes to them. Even more powerful, Observables provide operators like map, forEach, filter, and reduce, similar to an array, making them ideal for complex manipulation of data streams.
npm install rxjs
import { Observable } from 'rxjs'; const exampleObservable = new Observable<string>(subscriber => { let count = 0; setInterval(() => { subscriber.next(`Observable count: ${count++}`); if (count > 5) { subscriber.complete(); } }, 1000); }); exampleObservable.subscribe({ next(x) { console.log(x); }, error(err) { console.error('Something went wrong: ' + err); }, complete() { console.log('Done'); } });
In this Observable example, we create an Observable that emits a value every second. It stops after emitting 5 values. We then subscribe to this Observable and log each emitted value. After the Observable completes, ‘Done’ is printed to the console. If any error occurs, it would be logged to the console in the error callback.
Distinguishing Between Promise and Observable
Here are some key differences between a Promise and an Observable:
Single vs Multiple Values: As stated before, a Promise will resolve a single value or an error, whereas an Observable can emit multiple values over time.
Eager vs Lazy Execution: Promises are eager, which means once a Promise is called, it starts executing and will eventually resolve or reject. On the other hand, Observables are lazy, meaning they don’t execute until they are subscribed to.
Cancellation: One of the significant differences is the ability to cancel an operation. With Promises, once you have set it to execute, it will run to completion. There’s no looking back. However, Observables provide the functionality to cancel or unsubscribe from an ongoing operation, which is a powerful feature.
Operators: While Promises can be chained using .then, the functionality is relatively basic. In contrast, Observables have a wide array of operators like map, filter, and reduce, to name a few, which can be used for powerful data transformations before the data is consumed.
Which Should You Use: Promise or Observable?
Deciding between Promise and Observable depends on your specific use case. A Promise might be an optimal choice if you have a one-time event, such as a request to a server that retrieves a single chunk of data. However, if you’re dealing with a series of values over time, such as user interface events or streaming data, Observables provide a far superior and more flexible API.
Remember that Observables can be converted to Promises if needed, giving you the best of both worlds when the situation demands it. This is a powerful feature, providing flexibility to the programmer to choose the right tool for the right task.
Conclusion
Promises and Observables are powerful tools for handling asynchronous operations in JavaScript/TypeScript. While they have similarities, understanding the differences between
Useful Links
https://dev.to/manthanank/difference-between-promises-and-observables-380e