[AngularJS] Promises: Chain Promises - 2. Chaining multiple asynchronous (server-) calls
Chaining multiple asynchronous (server-) calls
Imagine having a user id in you application. Now you want to load the details of the staff associated with the user account. One way of doing this is to first load the user details which might contain the id of the associated staff. Once we have this id we can then load the details of this user. In this situation we have to chain two asynchronous tasks. Using callback function this would be a quite complicated undertaken resulting in ugly and difficult to understand code, specifically if we also have to implement a robust exception handling. Using promises on the other hand makes the implementation really simple.
and this is the definition of the loadData function triggered by the button click. We define it in our TestCtrl controller.
Here we can see loadUser(), this function MUST return a promise.
The return value of this call contains amongst other values the id of the associated staff. Once we have that staff id we load the staff details (loadStaff on line 65). Finally we display the staff details as string in an alert box (line 67). In a real application we would probably use the Angular $http service or the $resourceservice to make a server call and get the data.
and the loadStaff like this
Read More: http://lostechies.com/gabrielschenker/2014/02/04/angularjspart-11-promises/