Promises are a design pattern that represents a single value that will be returned at some point in the future. They are often used to handle asynchronous operations, such as fetching data from a server or waiting for a user’s input. Promises have a few key properties: they are only called once, they cannot be cancelled, and they cannot be called again after they have been fulfilled or rejected.
Here is an example of a Promise in JavaScript:
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
// Fetch data from server
const data = {
name: 'John Doe',
age: 34,
email: '[email protected]'
};
// Resolve the Promise with the data
resolve(data);
}, 2000);
});
}
// Use the Promise
fetchData().then(data => {
// Do something with the data
console.log(data);
});
On the other hand, Observables are a design pattern that represents a stream of values that can be emitted over time. They are often used to handle asynchronous operations that may emit multiple values, such as user input events or real-time data streams. Observables have a few key properties: they can be cancelled, they can be called multiple times, and they can emit multiple values.
Here is an example of an Observable in JavaScript using the RxJS library:
const input$ = Rx.Observable.fromEvent(document.querySelector('input'), 'input');
input$.subscribe(event => {
console.log(event.target.value);
});
In summary, the main difference between Promises and Observables is that Promises represent a single value, while Observables represent a stream of values. Promises are called once and cannot be cancelled, while Observables can be cancelled and can be called multiple times.