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

AngularJS Promise

发布时间:2020-12-17 10:00:14 所属栏目:安全 来源:网络整理
导读:场景: 前端JS 异步,嵌套层次太多,维护时 无比痛苦(去年做的一个系统项目,现在回想起来,那时候够耐心的,那么多嵌套,搞的逻辑复杂多端) 诸如以下现象: function(arg1,arg2,function(){ function(arg1,function(){ function(arg1,function(){ ...... }

场景:

前端JS 异步,嵌套层次太多,维护时 无比痛苦(去年做的一个系统项目,现在回想起来,那时候够耐心的,那么多嵌套,搞的逻辑复杂多端)

诸如以下现象:

function(arg1,arg2,function(){
    function(arg1,function(){
        function(arg1,function(){
             ......
        })
    })   
})


解决法子:


Promise是一个接口,它用来处理的对象具有这样的特点:在未来某一时刻(主要是异步调用)会从服务端返回或者被填充属性。其核心是,promise是一个带有then()函数的对象。

q服务是AngularJS中自己封装实现的一种Promise实现,相对与Kris Kwal's Q要轻量级的多。
先介绍一下$q常用的几个方法:

  • defer() 创建一个deferred对象,这个对象可以执行几个常用的方法,比如resolve,reject,notify等
  • all() 传入Promise的数组,批量执行,返回一个promise对象
  • when() 传入一个不确定的参数,如果符合Promise标准,就返回一个promise对象

语法:

var deferred = $q.defer();
var promise = deferred.promise;

// assign behavior before resolving
promise.then(function (data) {
  console.log('before:',data);
});

deferred.resolve('done ');

多个 function 异步执行:
defer
.then(a,b)
.then(a,b)
.catch()
.finally()


all()的用法:

可以把多个primise的数组合并成一个。当所有的promise执行成功后,会执行后面的回调。回调中的参数,是每个promise执行的结果。
当批量的执行某些方法时,就可以使用这个方法

function PromiseCtrl($scope,$q,$timeout) {
    // Our promise function with its delay as argument
    var getPromise = function(delay) {
        // Creates a Deferred object
        var deferred = $q.defer();
                       
        $timeout(function() {
            // Resolve the promise at the end of the delay if said delay was > 0
            if(delay > 0) {
                deferred.resolve("Success");
            } else {
                deferred.reject("Fail");
            }
        },delay);
        
        // The promise of the deferred task
        return deferred.promise;
    };
    
    // Init
    $scope.result = "Waiting";
    
    /*
	 * Combines multiple promises into a single promise
     * that will be resolved when all of the input promises are resolved
	 */
    $q.all([
            getPromise(1000),getPromise(2000),getPromise(3000) // <--- Try something less than 0
        ]).then(function(value) {
        // Success callback where value is an array containing the success values
        $scope.result = value;       
    },function(reason) {
        // Error callback where reason is the value of the first rejected promise
        $scope.result = reason;
    });
}

(编辑:李大同)

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

    推荐文章
      热点阅读