[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.

image

 

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.

 

image

and the loadStaff like this

image

 

Read More: http://lostechies.com/gabrielschenker/2014/02/04/angularjspart-11-promises/

posted @   Zhentiw  阅读(186)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示