Explain the difference between Promise and Observable in Angular?
Explain the difference between Promise and Observable in Angular?
In Angular, both Promises and Observables are used to handle asynchronous operations, but they have distinct characteristics and use cases.
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].
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].
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào