[笔记]jQuery与Angular中promise的区别

前端之家收集整理的这篇文章主要介绍了[笔记]jQuery与Angular中promise的区别前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

近期,为了新项目的开发,从老的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');
});

控制台下输出

《[笔记]jQuery与Angular中promise的区别》

同样是这样,我们来看下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');
    });
}]);

结果很意外

《[笔记]jQuery与Angular中promise的区别》

再测试发现,再在后面增加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吧。

猜你在找的程序笔记相关文章