本文實(shí)例講述了AngularJS中的promise用法。分享給大家供大家參考,具體如下:
JavaScript異步回調(diào)有好處也有壞處,回調(diào)函數(shù)大量嵌套十分復(fù)雜.所以javascript中還有另一種異步處理模式叫promises.在AngularJS中的實(shí)現(xiàn)就是$q服務(wù).
下面是一些小例子.
then,catch,finally
在鏈最后的 catch 為整個(gè)鏈?zhǔn)教幚硖峁┮粋€(gè)異常處理點(diǎn)
在鏈最后的 finally 總是會(huì)被執(zhí)行,不管 promise 被處理或者被拒絕,起清理作用
<!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="bootstrap.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > <script src="jQuery.min.js"></script> <script src="angular.min.js"></script> <script src="bootstrap.min.js"></script> <script type="text/javascript"> var myapp = angular.module('myapp', []); myapp.controller('myController', function($scope, $q) { $scope.send = function() { var deferred = $q.defer(); var promise = deferred.promise; promise .then(function() { console.log('resolve.....') }, function() { console.log('reject.....'); }, function() { console.log('notify.....'); }) .catch(function() { console.log('catch..error..') }) .finally(function() { console.log('anywhere will be called..'); }); deferred.reject('resolve'); }; }); </script> <style type="text/css"> </style> </head> <body ng-app="myapp"> <div ng-controller="myController"> <button class="btn" ng-click="send()">click</button> </div> </body></html>then第三個(gè)參數(shù)(表征狀態(tài))的應(yīng)用
<!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="bootstrap.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > <script src="jquery.min.js"></script> <script src="angular.min.js"></script> <script src="bootstrap.min.js"></script> <script type="text/javascript"> var myapp = angular.module('myapp', []); myapp.controller('myController', function($scope, dataService) { $scope.send = function() { dataService.getData() .then(function success(data) { console.log(data); }, function error(error) { console.log(error); }, function status(process) { console.log(process); }); }; }); myapp.factory('dataService', function($q, $interval) { return { getData : function() { var deferred = $q.defer(); var process = 0; var interval = $interval(function() { process += 10; deferred.notify(process); //reject之后不再繼續(xù)運(yùn)行 // if (process == 50) { // deferred.reject(process); // } if (process >= 100) { $interval.cancel(interval); deferred.resolve(process); } }, 1000); return deferred.promise; } }; }); </script> <style type="text/css"> </style> </head> <body ng-app="myapp"> <div ng-controller="myController"> <button class="btn" ng-click="send()">click</button> </div> </body></html>
新聞熱點(diǎn)
疑難解答
圖片精選