zoukankan      html  css  js  c++  java
  • ANGULAR JS PROMISE使用

    Promise是一种模式,以同步操作的流程形式来操作异步事件,避免了层层嵌套,可以链式操作异步事件。

    我们知道,在编写javascript异步代码时,callback是最最简单的机制,可是用这种机制的话必须牺牲控制流、异常处理和函数语义化为代价,甚至会让我们掉进出现callback大坑,而promise解决了这个问题。

     

    下面实例是angularjs 的promise的实现方式:

    <!DOCTYPE html>
    <html ng-app="app">
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="assets/angular.min.js"></script>
    </head>
    <body ng-controller="ctrl">
    
    <script type="text/javascript">
    
    var  app = angular.module("app",[]);
    app.controller('ctrl', ['$scope','$q',function($scope,$q){
        
        function okToGreet(name){
            return name === 'Robin Hood';
        }
    
        function asyncGreet(name) {
            var deferred = $q.defer();
    
            setTimeout(function() {
                // 因为这个异步函数fn在未来的异步执行,我们把代码包装到 $apply 调用中,一边正确的观察到 model 的改变
                $scope.$apply(function() {
                    deferred.notify('About to greet ' + name + '.');
    
                    if (okToGreet(name)) {
                        deferred.resolve('Hello, ' + name + '!');
                    } else {
                        deferred.reject('Greeting ' + name + ' is not allowed.');
                    }
                });
            }, 1000);
    
            return deferred.promise;
        }
    
        var promise = asyncGreet('Robin Hood');
        promise.then(function(greeting) {
            console.info('Success: ' + greeting);
        }, function(reason) {
            console.info('Failed: ' + reason);
        }, function(update) {
            console.info('Got notification: ' + update);
        });
    }]);
    
    
    </script>
    </body>
    </html>

     

    其中我们可以通过defered.notify ,defered.resolve,defered.reject 传递参数给其后的链式操作。

  • 相关阅读:
    js中的同步与异步
    全局刷新 局部刷新
    url的组成
    Linux云自动化运维第十二课
    Linux云自动化运维第十一课
    Linux云自动化运维第十课
    Linux云自动化运维第九课
    Linux云自动化运维第八课
    Linux云自动化运维第七课
    Linux云自动化运维第六课
  • 原文地址:https://www.cnblogs.com/yg_zhang/p/4799480.html
Copyright © 2011-2022 走看看