Promises and observables are both mechanisms used in JavaScript for handling asynchronous operations, but they have different characteristics and usage patterns.
Promises:
- Promise is an object representing the eventual completion or failure of an asynchronous operation and its resulting value.
- It has states: pending (initial state), fulfilled (operation completed successfully), or rejected (operation failed).
- A Promise can be created using the
new Promise()
constructor, taking a function withresolve
andreject
parameters. - It provides a cleaner way to write asynchronous code compared to callbacks, allowing chaining of
.then()
and.catch()
methods. .then()
is used to handle the resolved value, and.catch()
is used to catch any errors.- Promises are not cancellable, and once settled (fulfilled or rejected), they remain in that state.