3

I am going through Angular2 startup.

On the file named 'app/crisis-center/crisis.service.ts' here: https://angular.io/resources/live-examples/router/ts/plnkr.html

They have this line:

var crisesPromise = Promise.resolve(crises);

What is the purpose of this exactly? I have read about general Promise.Resolve JavaScript usage, but still don't quite follow why it is being used here.

Is it merely to wrap an instance of the crises array in a Singleton like manner? I don't quite see the benefit or purpose over just accessing the crises array directly.

SnareChops
  • 13,175
  • 9
  • 69
  • 91
rygo6
  • 1,929
  • 22
  • 30
  • Possible duplicate of [When should I call Promise.resolve() directly?](http://stackoverflow.com/questions/32461170/when-should-i-call-promise-resolve-directly) – Bergi Jun 01 '16 at 05:35

2 Answers2

8

Is it merely to wrap an instance of the crises array in a Singleton like manner? I don't quite see the benefit or purpose over just accessing the crises array directly.

It is to create a promise when you already know the answer. Main use case : The consumer of the API expects you to return a promise. But since you already know the answer you can use Promise.resolve to create an already resolved promise and return it.

basarat
  • 261,912
  • 58
  • 460
  • 511
0

If you look at the hero-list.component.ts:

ngOnInit() {
    this._service.getHeroes().then(heroes => this.heroes = heroes)
}

They are calling the service method getHeroes which returns a Promise and following that, they call the then method on that returned promise, including the callback that tells the promise object what to do once it gets resolved.

In the hero.service.ts they have the heroes as a local array and they don't have to do a server call, but in a real app you won't have this data here, you'd call a remote server for that data, so if you would return the Array directly instead of a wrapping it with a Promise, in the future when you change the service to call to a real http method you'd have to change both the service and all the components that use it, to receive a Promise instead of an Array.

By wrapping the local Array into a Promise you can make sure that the code on the component will already work with a Promise, so it doesn't matter if that promise gets resolved syncronously or asyncronously, nor you care, it'll work correctly on both scenarios, so you can start out by testing your services with locally mocked data, return that data wrapped into Promises and change them later on into real http calls only by modifying the Services without touching all the components that use that Service.

Langley
  • 5,326
  • 2
  • 26
  • 42