Promise执行链
来源:互联网 发布:汽车融资租赁软件 编辑:程序博客网 时间:2024/06/14 13:37
Promise执行链
- 由于javascript的非阻塞式的特性,使得很多写惯阻塞式程序的人在刚开始接触原生js时,显得很难适应,本篇文章就为大家解惑Promise执行链。
首先promise对象的出现,是专门为异步代码同步化所设计的。
- 抛开promise,仅用callback函数进行处理,显得捉襟见肘。
注:代码使用angular js框架,与其他原生js,例如nodejs原理相同。
.controller('appCtrl', function($timeout, $scope){ function add(x, y, callback, errorCallback) { $timeout(function() { callback(x + y) }, 100); } var startTime = Date.now(); add(5, 2, function(result) { add(result, 1, function(result) { add(result, 3, function(result) { $scope.result = result; $scope.elapsedTime = Date.now() - startTime; }, function(error){ /* handle error */ }) }, function(error){ /* handle error */ }) }, function(error){ /* handle error */ }); })
陷入无穷无尽的callback调用之中。。。
虽然最初使用promise会显得不适应,但是对于代码本身来说,还是比callback条理性更强。
下面的代码使用了q.defer() 来生成promise结构,与nodejs当中的q 使用类似。
.controller('appCtrl', function($q, $scope){ function add(x, y) { var q = $q.defer(); setTimeout(function() { var result = x + y; if (result >= 0) { q.resolve(result); } else { q.reject("negative value: " + result); } }, 100); return q.promise; } var startTime = Date.now(); add(5, 2) .then(function(result) { // 1 #1 --> return add(result, -10); #2 --> return add(result, 3); }) .then(function(result) { // 2 return add(result, 1); }) .then(function(result) { // 3 $scope.result = result; }) .catch(function(failure) { // 4 $scope.failure = failure; }) .finally(function() { // 5 $scope.elapsedTime = Date.now() - startTime; }) })
在链中使用#1 — return add(result, -10);
会使得add函数,reject出一条异常错误。所以promise链的执行顺序为: 1 –> 4 –> 5 。
我们可以看到promise的catch机制,可以捕捉上面链中的任意一个异常。
使用#2 — return add(result, 3);
promise链正常执行,顺序为:1 –> 2 –> 3 –> 5
但是,我们有时希望不经过统一的catch处理,而是在每一个子链当中进行异常处理,这时只需要在链中定义第二个回调函数即可。
var startTime = Date.now(); add(5, 2) .then(function(result) { // 1 return add(result, -10); }) .then(function(result) { // 2.1 return add(result, 1); }, function(error) { // 2.2 return add(result, 0); }) .then(function(result) { // 3 $scope.result = result; }) .catch(function(failure) { // 4 $scope.failure = failure; }) .finally(function() { // 5 $scope.elapsedTime = Date.now() - startTime; })
我们可以看到在//1 步骤中reject的异常,被//2 步骤中第二个异常回调函数(2.2)捕捉。
具体执行顺序为:1 –> 2.2 –> 3 –> 5
1 0
- Promise执行链
- Promise的顺序执行
- JavaScript promise 链,并行promise
- Promise 异步函数顺序执行
- promise的异常链
- promise
- Promise
- Promise
- Promise
- Promise
- Promise
- Promise
- promise
- promise
- promise
- promise
- Promise
- Promise
- MySQL中间件
- web前端之路(2)--初涉"页面表现原则"
- Python学习笔记——dict和set
- app某界面布局分析
- NSString属性什么时候用copy,什么时候用strong?
- Promise执行链
- Excel之数理统计
- android SwipeMenuListView ScrollView 滑动冲突
- data-role="navbar" 导航框样式被挤下去
- Ruby on Rails,使用where方法对持久化对象进行条件查询
- Android 进程状态的概念
- 157,UIWebView
- Saitama Destroys Hotel
- 致敬我的2015