目录 搜索
AngularJS API Reference auto auto/service auto/service/$injector auto/service/$provide ng ng/directive ng/directive/a ng/directive/form ng/directive/input ng/directive/input[checkbox] ng/directive/input[date] ng/directive/input[dateTimeLocal] ng/directive/input[email] ng/directive/input[month] ng/directive/input[number] ng/directive/input[radio] ng/directive/input[text] ng/directive/input[time] ng/directive/input[url] ng/directive/input[week] ng/directive/ngApp ng/directive/ngBind ng/directive/ngBindHtml ng/directive/ngBindTemplate ng/directive/ngBlur ng/directive/ngChange ng/directive/ngChecked ng/directive/ngClass ng/directive/ngClassEven ng/directive/ngClassOdd ng/directive/ngClick ng/directive/ngCloak ng/directive/ngController ng/directive/ngCopy ng/directive/ngCsp ng/directive/ngCut ng/directive/ngDblclick ng/directive/ngDisabled ng/directive/ngFocus ng/directive/ngForm ng/directive/ngHide ng/directive/ngHref ng/directive/ngIf ng/directive/ngInclude ng/directive/ngInit ng/directive/ngKeydown ng/directive/ngKeypress ng/directive/ngKeyup ng/directive/ngList ng/directive/ngModel ng/directive/ngModelOptions ng/directive/ngMousedown ng/directive/ngMouseenter ng/directive/ngMouseleave ng/directive/ngMousemove ng/directive/ngMouseover ng/directive/ngMouseup ng/directive/ngNonBindable ng/directive/ngOpen ng/directive/ngPaste ng/directive/ngPluralize ng/directive/ngReadonly ng/directive/ngRepeat ng/directive/ngSelected ng/directive/ngShow ng/directive/ngSrc ng/directive/ngSrcset ng/directive/ngStyle ng/directive/ngSubmit ng/directive/ngSwitch ng/directive/ngTransclude ng/directive/ngValue ng/directive/script ng/directive/select ng/directive/textarea ng/filter ng/filter/currency ng/filter/date ng/filter/filter ng/filter/json ng/filter/limitTo ng/filter/lowercase ng/filter/number ng/filter/orderBy ng/filter/uppercase ng/function ng/function/angular.bind ng/function/angular.bootstrap ng/function/angular.copy ng/function/angular.element ng/function/angular.equals ng/function/angular.extend ng/function/angular.forEach ng/function/angular.fromJson ng/function/angular.identity ng/function/angular.injector ng/function/angular.isArray ng/function/angular.isDate ng/function/angular.isDefined ng/function/angular.isElement ng/function/angular.isFunction ng/function/angular.isNumber ng/function/angular.isObject ng/function/angular.isString ng/function/angular.isUndefined ng/function/angular.lowercase ng/function/angular.module ng/function/angular.noop ng/function/angular.toJson ng/function/angular.uppercase ng/object ng/object/angular.version ng/provider ng/provider/$animateProvider ng/provider/$compileProvider ng/provider/$controllerProvider ng/provider/$filterProvider ng/provider/$httpProvider ng/provider/$interpolateProvider ng/provider/$locationProvider ng/provider/$logProvider ng/provider/$parseProvider ng/provider/$rootScopeProvider ng/provider/$sceDelegateProvider ng/provider/$sceProvider ng/service ng/service/$anchorScroll ng/service/$animate ng/service/$cacheFactory ng/service/$compile ng/service/$controller ng/service/$document ng/service/$exceptionHandler ng/service/$filter ng/service/$http ng/service/$httpBackend ng/service/$interpolate ng/service/$interval ng/service/$locale ng/service/$location ng/service/$log ng/service/$parse ng/service/$q ng/service/$rootElement ng/service/$rootScope ng/service/$sce ng/service/$sceDelegate ng/service/$templateCache ng/service/$timeout ng/service/$window ng/type ng/type/$cacheFactory.Cache ng/type/$compile.directive.Attributes ng/type/$rootScope.Scope ng/type/angular.Module ng/type/form.FormController ng/type/ngModel.NgModelController ngAnimate ngAnimate/provider ngAnimate/provider/$animateProvider ngAnimate/service ngAnimate/service/$animate ngCookies ngCookies/service ngCookies/service/$cookies ngCookies/service/$cookieStore ngMessages ngMessages/directive ngMessages/directive/ngMessage ngMessages/directive/ngMessages ngMock ngMock/function ngMock/function/angular.mock.dump ngMock/function/angular.mock.inject ngMock/function/angular.mock.module ngMock/object ngMock/object/angular.mock ngMock/provider ngMock/provider/$exceptionHandlerProvider ngMock/service ngMock/service/$exceptionHandler ngMock/service/$httpBackend ngMock/service/$interval ngMock/service/$log ngMock/service/$timeout ngMock/type ngMock/type/angular.mock.TzDate ngMockE2E ngMockE2E/service ngMockE2E/service/$httpBackend ngResource ngResource/service ngResource/service/$resource ngRoute ngRoute/directive ngRoute/directive/ngView ngRoute/provider ngRoute/provider/$routeProvider ngRoute/service ngRoute/service/$route ngRoute/service/$routeParams ngSanitize ngSanitize/filter ngSanitize/filter/linky ngSanitize/service ngSanitize/service/$sanitize ngTouch ngTouch/directive ngTouch/directive/ngClick ngTouch/directive/ngSwipeLeft ngTouch/directive/ngSwipeRight ngTouch/service ngTouch/service/$swipe
文字

AngularJS: API: ng/service/$q


$q

  1. - service in module ng

A promise/deferred implementation inspired by Kris Kowal's Q.

The CommonJS Promise proposal describes a promise as an interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time.

From the perspective of dealing with error handling, deferred and promise APIs are to asynchronous programming what try, catch and throw keywords are to synchronous programming.

  // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet`
  // are available in the current lexical scope (they could have been injected or passed in).

  Function asyncGreet(名称) {
    var deferred = $q.defer();

    setTimeout(Function() {
      deferred.notify('About to greet ' + name + '.');

      if (okToGreet(名称)) {
        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) {
    alert('Success: ' + greeting);
  }, Function(reason) {
    alert('Failed: ' + reason);
  }, Function(update) {
    alert('Got notification: ' + update);
  });

At first it might not be obvious why this extra complexity is worth the trouble. The payoff comes in the way of guarantees that promise and deferred APIs make, see https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.

Additionally the promise api allows for composition that is very hard to do with the traditional callback (CPS) approach. For more on this please see the Q documentation especially the section on serial or parallel joining of promises.

The Deferred API

A new instance of deferred is constructed by calling $q.defer().

The purpose of the deferred object is to expose the associated Promise instance as well as APIs that can be used for signaling the successful or unsuccessful completion, as well as the status of the task.

方法

  • resolve(value) – resolves the derived promise with the value. If the value is a rejection constructed via $q.reject, the promise will be rejected instead.
  • reject(reason) – rejects the derived promise with the reason. This is equivalent to resolving it with a rejection constructed via $q.reject.
  • notify(value) - provides updates on the status of the promise's execution. This may be called multiple times before the promise is either resolved or rejected.

属性

  • promise – {Promise} – promise object associated with this deferred.

The Promise API

A new promise instance is created when a deferred instance is created and can be retrieved by calling deferred.promise.

The purpose of the promise object is to allow for interested parties to get access to the result of the deferred task when it completes.

方法

  • then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. 此外, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.

    This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method.

  • catch(errorCallback) – shorthand for promise.then(null, errorCallback)

  • finally(callback) – allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information.

    Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible.

Chaining promises

Because calling the then method of a promise returns a new derived promise, it is easily possible to create a chain of promises:

  promiseB = promiseA.then(Function(result) {
    return result + 1;
  });

  // promiseB will be resolved immediately after promiseA is resolved and its value
  // will be the result of promiseA incremented by 1

It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain. This makes it possible to implement powerful APIs like $http's response interceptors.

Differences between Kris Kowal's Q and $q

There are two main differences:

  • $q is integrated with the $rootScope.Scope Scope model observation mechanism in angular, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI.
  • Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains all the important functionality needed for common async tasks.

    Testing

     it('should simulate promise', inject(Function($q, $rootScope) {
       var deferred = $q.defer();
       var promise = deferred.promise;
       var resolvedValue;
    
       promise.then(Function(value) { resolvedValue = value; });
       expect(resolvedValue).toBeUndefined();
    
       // Simulate resolving of promise
       deferred.resolve(123);
       // Note that the 'then' function does not get called synchronously.
       // This is because we want the promise API to always be async, whether or not
       // it got called synchronously or asynchronously.
       expect(resolvedValue).toBeUndefined();
    
       // Propagate promise resolution to 'then' functions using $apply().
       $rootScope.$apply();
       expect(resolvedValue).toEqual(123);
     }));

依赖

  • $rootScope

方法

  • defer();

    Creates a Deferred object which represents a task which will finish in the future.

    返回值

    Deferred

    Returns a new instance of deferred.

  • reject(reason);

    Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it.

    When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject.

      promiseB = promiseA.then(Function(result) {
        // success: do something and resolve promiseB
        //          with the old or a new result
        return result;
      }, Function(reason) {
        // error: handle the error if possible and
        //        resolve promiseB with newPromiseOrValue,
        //        otherwise forward the rejection to promiseB
        if (canHandle(reason)) {
         // handle the error and recover
         return newPromiseOrValue;
        }
        return $q.reject(reason);
      });

    参数

    参数 类型 详述
    reason *

    Constant, message, exception or an object representing the rejection reason.

    返回值

    Promise

    Returns a promise that was already resolved as rejected with the reason.

  • when(value);

    Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

    参数

    参数 类型 详述
    value *

    Value or a promise

    返回值

    Promise

    Returns a promise of the passed value or promise

  • all(promises);

    Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

    参数

    参数 类型 详述
    promises Array.<Promise>Object.<Promise>

    An array or hash of promises.

    返回值

    Promise

    Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.


上一篇: 下一篇: