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(){ ...... }) }) })
q服务是AngularJS中自己封装实现的一种Promise实现,相对与Kris Kwal's Q要轻量级的多。
语法: 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()
可以把多个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; }); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |