Câu hỏi phỏng vấn Angular
Câu hỏi

What is the difference between promise and observable ?

Câu trả lời

In Angular, both Promises and Observables are used to handle asynchronous operations, but they have distinct characteristics and use cases.

Promises

A Promise in Angular is a JavaScript object that represents the eventual completion or failure of an asynchronous operation and its resulting value. Here are some key features of Promises:

  • Single Value: A Promise handles a single event when an asynchronous operation completes or fails. It emits a single value and cannot emit multiple values over time[1][2][3].
  • Eager Execution: Promises start executing immediately upon creation, regardless of whether there is a listener attached to them[4].
  • Non-Cancellable: Once initiated, a Promise cannot be canceled. It will eventually resolve or reject[1][2][3].
  • Error Handling: Promises use the .then() for resolving and .catch() for rejecting, which are used to handle errors and successful responses[1][2].

Observables

Observables, provided by the RxJS library in Angular, offer a more powerful and flexible approach to handling asynchronous and event-based programs. They have the following characteristics:

  • Multiple Values: Observables can emit multiple values over time, making them suitable for handling a stream of events[1][2][3].
  • Lazy Execution: An Observable does not start emitting data until it has a subscriber, making it lazy. This is useful for scenarios where the data may not be needed immediately or where the data generation is costly[3][4].
  • Cancellable: Subscriptions to Observables can be canceled using the unsubscribe() method, which stops the listener from receiving further values. This is particularly useful for long-lived or resource-intensive operations...
middle

middle

Gợi ý câu hỏi phỏng vấn

expert

How does Ivy affect the (Re)build time?

senior

Angular 9: What are some new features in Angular 9?

junior

What is Interpolation?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào