Promises

Go back to Tutorial

Promises are a pattern that helps with one particular kind of asynchronous programming: a function (or method) that returns a single result asynchronously. One popular way of receiving such a result is via a callback (“callbacks as continuations”):

asyncFunction(arg1, arg2,

result => {

console.log(result);

});

Promises provide a better way of working with callbacks: Now an asynchronous function returns a Promise, an object that serves as a placeholder and container for the final result. Callbacks registered via the Promise method then() are notified of the result:

asyncFunction(arg1, arg2)

.then(result => {

console.log(result);

});

The hero service makes a Promise

A Promise essentially promises to call back when the results are ready. You ask an asynchronous service to do some work and give it a callback function. The service does that work and eventually calls the function with the results or an error.

Update the HeroService with this Promise-returning getHeroes() method:

src/app/hero.service.ts (excerpt)

getHeroes(): Promise<Hero[]> {

return Promise.resolve(HEROES);

}

You’re still mocking the data. You’re simulating the behavior of an ultra-fast, zero-latency server, by returning an immediately resolved Promise with the mock heroes as the result.

Act on the Promise

As a result of the change to HeroService, this.heroes is now set to a Promise rather than an array of heroes.

src/app/app.component.ts (getHeroes – old)

getHeroes(): void {

this.heroes = this.heroService.getHeroes();

}

You have to change the implementation to act on the Promise when it resolves. When the Promise resolves successfully, you’ll have heroes to display.

Pass the callback function as an argument to the Promise’s then() method:

src/app/app.component.ts (getHeroes – revised)

getHeroes(): void {

this.heroService.getHeroes().then(heroes => this.heroes = heroes);

}

As described in Arrow functions, the ES2015 arrow function in the callback is more succinct than the equivalent function expression and gracefully handles this. The callback sets the component’s heroes property to the array of heroes returned by the service.

The app is still running, showing a list of heroes, and responding to a name selection with a detail view.

Go back to Tutorial

Share this post
[social_warfare]
Angular 7 Promises, and Route Protection
Observables

Get industry recognized certification – Contact us

keyboard_arrow_up