Promises in Angular
Promises in Angular
In Angular, Promises provide a mechanism for
handling asynchronous operations that resolve a single
value or an error in the future. They are ideal for
tasks that complete once, such as API calls or timers.
Key Features of Promises
- Promises
resolve only once—either with a success value (resolve) or an error
(reject). They do not support multiple emissions like Observables.
- Promises
begin executing immediately when they are created. They
are not lazy and cannot be deferred like Observables.
- Once a
Promise starts, it cannot be cancelled. This limits their
flexibility in situations where you may want to abort the operation.
- Promises
work seamlessly with async/await, making asynchronous code easier to write
and understand.
- Typical Use
Cases
· One-time
data fetching
· Wrapping
native browser APIs (e.g., Geolocation API)
· Simplifying
async logic in Angular services and components for single-result operations
A Promise uses:
- .then() for
handling success
- .catch() for
error handling
- .finally()
for executing logic after the result is known, regardless of outcome
Example: Making an HTTP Request Using Promises in Angular (via
fetch)
While Angular’s HttpClient returns Observables, you
can still use native fetch() for Promise-based requests.
// Fetch data from a public API using Promises
function fetchData(): Promise<string> {
return
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => {
if (!response.ok) {
throw new
Error("Network response was not ok");
}
return response.json();
})
.then(data => `Title: ${data.title}`);
}
// Using .then()
function usingThen() {
fetchData().then(result => {
console.log("Using .then():",
result);
}).catch(error => {
console.error("Error:", error);
});
}
// Using async/await
async function usingAsyncAwait() {
try {
const result = await fetchData();
console.log("Using
async/await:", result);
} catch (error) {
console.error("Error:", error);
}
}
// Call both for demonstration
usingThen();
usingAsyncAwait();
Sample Output:
Using .then(): Title: sunt aut facere repellat provident occaecati
excepturi optio reprehenderit
Using async/await: Title: sunt aut facere repellat provident
occaecati excepturi optio reprehenderit
Note:
· API
used: https://jsonplaceholder.typicode.com/posts/1
· You
can replace this with any real API endpoint.
· Customize
the output (e.g., show title, body, or the entire object).
Example: Simulating Async Behavior with a Timeout
// Simulated async function using Promise and setTimeout
function fetchData(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data
loaded");
}, 1000); // Simulate 1-second delay
});
}
function usingThen() {
fetchData().then(result => {
console.log("Using .then():",
result);
}).catch(error => {
console.error("Error:", error);
});
}
async function usingAsyncAwait() {
try {
const result = await fetchData();
console.log("Using
async/await:", result);
} catch (error) {
console.error("Error:", error);
}
}
// Execute both versions
usingThen();
usingAsyncAwait();
Sample Output:
Using .then(): Data loaded
Using async/await: Data loaded
Why Use Promises in Angular?
Promises offer a concise, readable, and effective way to manage single-result
asynchronous operations. When your use case does not require:
- multiple
values over time,
- stream
transformation,
- cancellation,
or
- fine-grained
subscription control,
Promises are often the simplest and most effective choice.
Their clean API and compatibility with modern JavaScript
(async/await) make them particularly useful for straightforward, one-off async
tasks in Angular applications.
Summary
In Angular, a Promise is a useful abstraction for
managing simple asynchronous workflows. It is best suited for operations where
you expect only a single result. Promises are readable,
predictable, and work well with async/await, which improves the structure of
asynchronous logic.
However, for most Angular applications, Observables (from
RxJS) are preferred due to their ability to handle multiple values, reactive
streams, operators, and cancellation support. Still, a strong understanding of
Promises is essential for integrating with native browser APIs, external
libraries, or one-time operations.
Comments
Post a Comment