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

Explain the difference between Promise and Observable in Angular?

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.

Promise

A Promise in Angular represents a single future value that is not available yet but is expected to be resolved or rejected at some point. Promises are eager, meaning they start executing immediately upon definition, regardless of whether a .then() or .catch() method is called. A Promise can only emit a single value, and once it is resolved or rejected, it is considered settled and cannot be used to emit additional values.

Promises have two possible states: resolved or rejected. They offer structured error handling with .then() for resolved states and .catch() for rejected ones. Promises are suitable for single asynchronous operations like reading data from a server or a file. However, they are not cancellable, which means once a Promise is initiated, it will run to completion and cannot be stopped[1][2][3][5][6].

Observable

Observables, on the other hand, can handle a sequence of asynchronous events over time. They are lazy, meaning they do not start executing until you subscribe to them, which is why they are referred to as lazy. Observables can emit multiple values and are cancellable, allowing you to unsubscribe from the source of the values, effectively canceling the operation.

Observables come from the RxJS library and provide a rich set of operators like map, filter, reduce, and others for transforming, combining, and working with the streams of data they represent. They are more complex than Promises and require a steeper learning curve, but they offer more flexibility and are suitable for handling multiple values over time, such as user input events or data streams[1][2][3][4][5][6].

Key Differences

  • Eager vs. Lazy: Promises are eager and execute immediately, while Obs...
middle

middle

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

middle

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

expert

Just-in-Time (JIT) vs Ahead-of-Time (AOT) compilation. Explain the difference

senior

What are the lifecycle hooks for components and directives?

Bình luận

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

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