JavaScript Promises vs. RxJS Observables
Observables and Promises are both used in asynchronous programming, but they have some important differences in how they handle data streams.
Promises represent a single value that will be resolved in the future, and once resolved, the promise is either fulfilled with a value or rejected with an error. Promises are typically used for operations that will produce a single result, such as fetching data from an API.
Example using Promise: Suppose we have an API endpoint that returns the current weather of a location in a Promise:
function getWeather(city) {
return fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=your_api_key`)
.then(response => response.json())
.then(data => {
const weather = data.weather[0].description;
return weather;
});
}
In the above code, the getWeather function takes a city as an argument and returns a Promise that will resolve with the weather description of the city. The Promise will either be fulfilled with the weather description or rejected with an error if the API call fails.