AngularJS: одновременное асинхронное выполнение двух сервисов

angular.module('MyModule', []).
	// controllers
	controller('FolderListCtrl', ['$scope', '$q', 'Async', 'Service1', 'Service2', function FolderListCtrl($scope, $q, Async, Service1, Service2) {
		$q.
			all([Async(Service1.query), Async(Service2.get)]).
			then(function (responses) {
				$scope.service1Res = responses[0];
				$scope.service2Res = responses[1];
			});
	}]).
	factory('Async', ['$q', function Async($q)
	{
		return function (ResCall, params) {
			var d = $q.defer();
			if (angular.isFunction(ResCall))
			{
				ResCall(params, function(response) {
					d.resolve(response);
				});
				return d.promise;
			}
			throw new Error('wrong invocation with ' + ResCall.toString());
		};
	}])

Можно было бы сделать дополнительные проверки, но мне они показались излишними.
По мотивам этого ответа: http://stackoverflow.com/a/15300364/801426

One Response so far.

  1. Круто. Про async и defer в JS я писал в своем блоге: http://plutov.by/post/javascript_memory

LEAVE A COMMENT