angular中的promise

angular中的promise用法

标签(空格分隔): angular


前言

Promise其实是一个规范,用类似then().then()这样的链式调用形式来处理因为异步带来意大利面条式的代码(多层函数嵌套)。
多层函数嵌套的原因是,因为js的异步特性,导致我们后面函数需要用到这个异步函数获取的数据或者结果时,必须要等异步函数处理完成。所以必须写在这个异步函数结尾。

Angular中的promise:$q

Angular把promise封装成了一个服务$q方便我们到处使用它。

当我们用console.log打印$q时,我们发现它是一个函数。实际还是封装了deferred对象。


 var $Q = function Q(resolver) {
    if (!isFunction(resolver)) {
      throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
    }

    var deferred = new Deferred();

    function resolveFn(value) {
      deferred.resolve(value);
    }

    function rejectFn(reason) {
      deferred.reject(reason);
    }

    resolver(resolveFn, rejectFn);

    return deferred.promise;
  };
  

然后我们console.log一下$q.defer()这个对象,发现控制台给我们一个Deferred对象,具体有以下方法

notify:用于通知then(),异步函数处理进度
promise:在处理做完notify,reject,或者resolve时,存储信息,然后作为一个promise对象返回
reject:数据获取失败,或处理函数出错,返回error原因
resolve:数据获取成功,返回正确的数据

使用$q方法:

  • $q是可以用在同步过程中的,我们先看在同步过程中的应用:
var app = angular.module('app',[]);
app.controller('MyCtrl',['$q','$scope','$timeout',function($scope,$q,$timeout){
    var defer = $q.defer();
    defer.resolve('data');
    defer.reject('error');
    defer.promise.then(function(data){
        console.log(data);//成功时显示data
    },function(error){
        console.log(error);//失败显示error
    })
}])

promise是一种模式,也适用于同步方式

  • 异步方式
var app = angular.module('app', []);
	app.controller('MyCtrl', ['$scope', '$q', '$timeout' ,function ($scope,$q,$timeout) {
		function async(sex){
			var defer = $q.defer();
		$timeout(function () {
				 
				defer.notify("查询性别中");
				if (sex == 'male') {
					defer.resolve(sex);
				}else {
					defer.reject(sex);
				}
			
			},2000);
			return defer.promise;
		}
		var sex = 'male';
		var promise = async(sex);
		promise.then(function (data) {
			console.log(data);
		}, function (error) {
			console.log(error);
		},function (notify) {
			console.log(notify);
		});
	}]);

我们在这里通过$timoue模拟异步,然后返回defer.promise。通过操作这个返回的promise给下个then函数使用。

其他方法

$q还有其他的方法,比如when,all,finally。
when:传递一个值
all:传递多个promise,必须全部执行成功,然后才能执行回调。
finally:是和then方法对应的函数,是所有的then执行完之后,然后执行他,无论成功失败,都会被执行。

这里在使用all时,需要在注意,每个defer只能传递一个值,resolve或者reject只能一个。需要用多个defer才能传递多个。
而且resolve是没有返回值的

var app = angular.module('app', []);
	app.controller('MyCtrl', ['$scope', '$q', '$timeout' ,function ($scope,$q,$timeout) {
		var a = $q.defer();
		var b = $q.defer();
		var c = $q.defer();
		a.resolve('a');
		b.resolve('b');
		c.resolve('c');
		$q.all([a.promise,b.promise,c.promise]).then(function (data) {
			console.log(data);
		}, function (error) {
			console.log(error);
		});
	}]);//如果把这里的all编程when,那么后面的data就不是一个数组,而是一组promise,when是原值传递
原文地址:https://www.cnblogs.com/thecatshidog/p/5622636.html