Home > Web Front-end > JS Tutorial > Observable v/s Promise

Observable v/s Promise

DDD
Release: 2024-11-27 21:22:11
Original
473 people have browsed it

Observable v/s Promise

*Observables * and *Promises * are both used to handle asynchronous operations in JavaScript, but they have some key differences:

Promises

  • Single Value: Promises handle a single asynchronous event and return a single value (or error).
  • Eager: Promises start executing immediately upon creation.
  • Not Cancellable: Once a Promise is initiated, it cannot be cancelled.
  • Syntax: Uses .then(), .catch(), and .finally() for chaining operations.

Example:

1

2

3

4

5

6

7

8

9

const promise = new Promise((resolve, reject) => {

  setTimeout(() => {

    resolve('Promise resolved!');

  }, 1000);

});

 

promise.then((value) => {

  console.log(value);

});

Copy after login

Observables

  • Multiple Values: Observables can emit multiple values over time.
  • Lazy: Observables do not start emitting values until they are subscribed to.
  • Cancellable: Subscriptions to Observables can be cancelled, stopping the emission of values.
  • Syntax: Uses .subscribe() to handle emitted values, errors, and completion.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import { Observable } from 'rxjs';

 

const observable = new Observable((subscriber) => {

  subscriber.next('First value');

  setTimeout(() => {

    subscriber.next('Second value');

    subscriber.complete();

  }, 1000);

});

 

const subscription = observable.subscribe({

  next(value) {

    console.log(value);

  },

  complete() {

    console.log('Observable complete');

  }

});

 

// To cancel the subscription

subscription.unsubscribe();

Copy after login

When to Use Each

  • Use Promises when you need to handle a single asynchronous operation.
  • Use Observables when you need to handle multiple asynchronous events or values over time, and when you need more control over the data stream (e.g., cancellation, transformation).

The above is the detailed content of Observable v/s Promise. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template