WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Expert · question 61 of 100

Can you explain the differences between Observables and Promises in handling asynchronous operations?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

Both Observables and Promises are used for handling asynchronous operations in JavaScript, but there are some differences between them.

Promises represent a single future value that will be resolved at some point. They have three states: pending, fulfilled, or rejected. Promises are consumed using the .then() and .catch() methods to handle the fulfillment or rejection of the promise.

Here’s an example of a Promise:

    const promise = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Hello, world!");
        }, 1000);
    });
    
    promise
    .then((result) => {
        console.log(result); // logs "Hello, world!" after 1 second
    })
    .catch((error) => {
        console.error(error);
    });

Observables, on the other hand, represent a stream of values that can be emitted over time. Observables can emit multiple values, and they can also emit errors. Observables are consumed using the .subscribe() method, which takes three callbacks: one for each emitted value, one for errors, and one for the completion of the observable.

Here’s an example of an Observable:

    const { Observable } = rxjs;
    
    const observable = new Observable((subscriber) => {
        setTimeout(() => {
            subscriber.next("Hello");
        }, 1000);
        setTimeout(() => {
            subscriber.next("World");
        }, 2000);
        setTimeout(() => {
            subscriber.complete();
        }, 3000);
    });
    
    observable.subscribe(
    (value) => console.log(value),
    (error) => console.error(error),
    () => console.log("Complete")
    );

In summary, Promises are used for handling a single future value, while Observables are used for handling a stream of values over time. Promises are consumed using .then() and .catch(), while Observables are consumed using .subscribe().

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics