Skip to content

MyTalkzHub

Menu
  • Home
  • Coding Articles
  • Marketing
  • Celebrity
  • How To
Menu
What is the difference between Promises and Observables

What is the difference between Promises and Observables

Posted on December 15, 2022

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.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How to Review Your Sales Funnel
  • How to Sell a Sales Funnel
  • How to Test a Sales Funnel
  • How to Track Your Sales Funnel
  • How to Use the Sales Funnel

Recent Comments

No comments to show.

Archives

  • January 2023
  • December 2022

Categories

  • Celebrity
  • Coding Articles
  • How To
  • Marketing
©2023 MyTalkzHub | Design: Newspaperly WordPress Theme