加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 创业 > C语言 > 正文

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

发布时间:2020-12-15 01:18:35 所属栏目:C语言 来源:网络整理
导读:近期,为了新项目的开发,从老的jquery分支中copy了些代码,在使用中遇到了些问题,特地看了下。 一、区别 直接切入正题,看jquery下的代码: var doThing = function () { var defer = $.Deferred(); defer.reject(); return defer.promise();};doThing().t

近期,为了新项目的开发,从老的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吧。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读