近期,为了新项目的开发,从老的jquery分支中copy了些代码,在使用中遇到了些问题,特地看了下。
一、区别
直接切入正题,看jquery下的代码:
var doThing = function () { var defer = $.Deferred(); defer.reject(); return defer.promise(); }; doThing().then(function () { console.log('success1'); },function () { console.log('error1'); }).then(function () { console.log('success2'); },function () { console.log('error2'); });
控制台下输出
同样是这样,我们来看下Angular下的情况,
app.controller('test',['$q',function($q) { var doThing = function() { var defer = $q.defer(); defer.reject(); return defer.promise; }; doThing().then(function () { console.log('success1'); },function () { console.log('error1'); }).then(function () { console.log('success2'); },function () { console.log('error2'); }); }]);
结果很意外
再测试发现,再在后面增加then,jQuery会一直fail下去,angular则是一直done下去。
二、ES6
这种情况下,到底谁错谁对呢?我们来看下es6中的用法。
(new Promise(function (resolve,reject) { reject(); })).then(function () { console.log('success1'); },function () { console.log('error2'); });
我们得到了和angular中同样的效果。
查阅资料,得到了对Promise更详细地介绍,Promise是一种链式的回调,每一个then或者catch返回的是一个已经处理过的promise对象,同时catch只能catch之前链条中出现的错误。
所以angular中的promise更接近标准的promise吧。