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

Can you explain the difference between Promise and Observable in Angular? In what scenario can we use
each case?

Câu trả lời

In Angular, both Promises and Observables are used to handle asynchronous operations, but they have distinct characteristics and are suited to different scenarios.

Promise

A Promise in Angular is a one-time guarantee of eventual completion or failure of an asynchronous operation. It can either resolve to a value if the operation is successful or reject with an error if the operation fails. Promises are eager, meaning they start executing immediately upon creation and are not cancellable once they have begun. They are well-suited for simpler, one-time asynchronous operations.

Characteristics of Promises:

  • Eager Execution: Executes immediately upon creation.
  • Single Value: Resolves or rejects a single value and then completes.
  • Non-Cancellable: Cannot be cancelled once execution starts.
  • Error Handling: Uses .then() for resolutions and .catch() for rejections.

Use Cases for Promises:

  • Single asynchronous operations like API calls where only one response is expected.
  • Operations where the cancellation is not required, such as finalizing a file upload or posting data to a server[1][2].

Observable

Observables, provided by the RxJS library, handle streams of multiple values over time and offer more powerful and complex functionalities compared to Promises. They are lazy, meaning they only start executing when a subscriber is present, and they are cancellable, which allows for stopping the execution chain when needed. Observables support a variety of operators like map, filter, reduce, and more, which can be used to handle complex data transformation and event handling scenarios.

Characteristics of Observables:

  • Lazy Execution: Only starts executing when subscribed to.
  • Multiple Values: Can emit multiple values over time.
  • Cancellable: Can be unsubscribed from, stopping further execution.
  • Powerful Operators: Supports operators for transformation, filtering, combination, error handling, etc.

Use Cases for Observables:

  • Handling events such as mouse movements or user input which are spread over time.
  • When the application requires a stream of data, like live stock prices or data feeds.
  • Complex transformations and combinations of asynchronous data streams.
  • Situations where cancellation of the operation might be necessary, such as aborting an HTT...
middle

middle

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

senior

Do I need to bootstrap custom elements?

middle

How do you categorize data binding types?

middle

What is AOT?

Bình luận

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

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