Angular學習:$q

原文地址:https://docs.angularjs.org/api/ng/service/$qhtml

$qhtml5

1.       - $qProvidergit

2.       - service in module ngangularjs

A service thathelps you run functions asynchronously, and use their return values (orexceptions) when they are done processing.es6

一個服務,能夠幫助您異步運行函數並在完成處理後使用其返回值(或異常)。github

This is a Promises/A+-compliantimplementation of promises/deferred objects inspired by Kris Kowal's Q.編程

這是Promise / A +兼容的promise / deferred對象的實現,靈感來自 Kris Kowal's Qapi

$q can be usedin two fashions --- one which is more similar to Kris Kowal's Q or jQuery'sDeferred implementations, and the other which resembles ES6 (ES2015) promisesto some degree.promise

$q能夠以兩種方式使用 --- 一種更相似於Kris KowalQjQueryDeferred實現,另外一種在某種程度上相似於ES6ES2015)的promisesapp

$q constructor

The streamlinedES6 style promise is essentially just using $q as a constructor which takesa resolver function as the first argument. Thisis similar to the native Promise implementation from ES6, see MDN.

流線化的ES6風格的promise本質上只是使用$q做爲一個構造函數,它接受一個resolver函數做爲第一個參數。這相似於ES6的原生的Promise實現,請參閱MDN

While theconstructor-style use is supported, not all of the supporting methods from ES6promises are available yet.

雖然構造函數風格的使用被支持,但並非全部的ES6 promises支持的方法均可用。

It can be usedlike so:

它能夠被相似這樣使用:

// for the purposeof this example let's assume that variables `$q` and `okToGreet`

// are available inthe current lexical scope (they could have been injected or passed in).

 

functionasyncGreet(name) {

  // perform some asynchronous operation,resolve or reject the promise when appropriate.

  return $q(function(resolve, reject) {

    setTimeout(function() {

      if (okToGreet(name)) {

        resolve('Hello, ' + name + '!');

      } else {

        reject('Greeting ' + name + ' is notallowed.');

      }

    }, 1000);

  });

}

 

var promise =asyncGreet('Robin Hood');

promise.then(function(greeting){

  alert('Success: ' + greeting);

}, function(reason){

  alert('Failed: ' + reason);

});

Note:progress/notify callbacks are not currently supported via the ES6-styleinterface.

注意:progress/notify回調函數當前不被經過ES6樣式的接口支持

Note: unlike ES6behavior, an exception thrown in the constructor function will NOT implicitlyreject the promise.

注意:不像ES6的行爲,一個異常會被拋出在當前的構造函數中,這將不會隱含reject這個promise

However, themore traditional CommonJS-style usage is still available, and documented below.

而後,更傳統的CommonJS-style的使用是仍舊可用的,而且展現在下面。

The CommonJS Promise proposal describes apromise as an interface for interacting with an object that represents theresult of an action that is performed asynchronously, and may or may not befinished at any given point in time.

The CommonJS Promise proposal 描述了一個promise做爲一個接口來和一個對象互動,這個對象表明着一個行爲的結果,這個行爲是異步執行的,而且可能會或者可能不會在任意指定的點上及時地被結束。

From theperspective of dealing with error handling, deferred and promise APIs are toasynchronous programming what trycatchand throw keywords are to synchronousprogramming.

從處理錯誤的角度來看,deferredpromise API是針對異步編程的,而trycatchthrow是針對同步編程的。

// for the purposeof this example let's assume that variables `$q` and `okToGreet`

// are available inthe current lexical scope (they could have been injected or passed in).

 

function asyncGreet(name){

  var deferred = $q.defer();

 

  setTimeout(function() {

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

 

    if (okToGreet(name)) {

      deferred.resolve('Hello, ' + name + '!');

    } else {

      deferred.reject('Greeting ' + name + ' is notallowed.');

    }

  }, 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 itmight not be obvious why this extra complexity is worth the trouble. The payoffcomes in the way of guarantees that promise and deferred APIs make, see https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.

首先,這額外的複雜性帶來的麻煩是值得的,這一點並不明顯。回報來自於promise

deferred API完成的一些保證。能夠參考:https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md

Additionally thepromise api allows for composition that is very hard to do with the traditionalcallback (CPS) approach. For moreon this please see the Q documentation especiallythe section on serial or parallel joining of promises.

額外的,這promise API容許合成,而這是傳統的回調(CPS)方法很難完成的。更多的信息請參看 Qdocumentation,特別是promise的串行或者並行的鏈接那一章節。

The Deferred API

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

一個新的deferred的實例是由調用 $q.defer()來構造的。

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

Deferred對象的目的是暴露出相關聯的Promise實例,就像那些能夠被用於去發出成功或者不成功完成的信號的API同樣,就像任務的狀態同樣。

Methods

方法

  • 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.
  • resolve(value) –用 value解析派生的promise。若是這個value是一個經過$q.reject 構造的rejection,取而代之的是,這個promise將會被拒絕。

 

  • reject(reason) – rejects the derived promise with the reason. This is equivalent to resolving it with a rejection constructed via $q.reject.
  • reject(reason) – 用 reason來拒絕這個派生的promise。這等同於去使用一個經過$q.reject 構造的rejection去解析它。
  • 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.
  • notify(value) – 在promise的執行狀態上提供更新。在這個promise或者被解析或者被拒絕以前能夠被調用屢次。

Properties

  • promise – {Promise} – promise object associated with this deferred.
  • promise – {Promise} – 用這個deferred關聯的promise對象。.

 

The Promise API

A new promiseinstance is created when a deferred instance is created and can be retrieved bycalling deferred.promise.

一個新的promise實例被建立,在一個deferred實例被建立,而且經過調用deferred.promise而獲取到。

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

這個promise對象的目的是容許有興趣的部分去能夠訪問deferred task的結果當這個task完成的時候。

Methods

  • 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. Additionally, 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 rejectedvia the return value of the successCallbackerrorCallback(unless that value is a promise, in which case it isresolved with the value which is resolved in that promise using promise chaining). Italso notifies via the return value of the notifyCallback method.The promise cannot be resolved or rejected from the notifyCallback method. TheerrorCallback and notifyCallback arguments are optional.

  • catch(errorCallback) – shorthand for promise.then(null, errorCallback)
  • finally(callback, notifyCallback) – 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.

Chaining promises

Because callingthe then method of a promise returns a new derivedpromise, it is easily possible to create a chain of promises:

promiseB =promiseA.then(function(result) {

  return result + 1;

});

 

// promiseB will beresolved immediately after promiseA is resolved and its value

// will be theresult of promiseA incremented by 1

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

Differences between KrisKowal's Q and $q

There are twomain differences:

  • $q is integrated with the $rootScope.Scope Scope model observation mechanism in AngularJS, 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 simulatepromise', 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 doesnot get called synchronously.

  // This is because we want the promiseAPI to always be async, whether or not

  // it got called synchronously orasynchronously.

  expect(resolvedValue).toBeUndefined();

 

  // Propagate promise resolution to'then' functions using $apply().

  $rootScope.$apply();

  expect(resolvedValue).toEqual(123);

}));

Dependencies

Usage

$q(resolver);

Arguments

Param

Type

Details

resolver

function(function, function)

Function which is responsible for resolving or rejecting the newly created promise. The first parameter is a function which resolves the promise, the second parameter is a function which rejects the promise.

Returns

Promise

The newly created promise.

Methods

  • defer();

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

Returns

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. Ifyou are dealing with the last promise in a promise chain, you don't need toworry about it.

When comparing deferreds/promises to the familiar behavior oftry/catch/throw, think of reject asthe throw keyword in JavaScript. This alsomeans that if you "catch" an error via a promise error callback andyou want to forward the error to the promise derived from the current promise,you have to "rethrow" the error by returning a rejection constructedvia reject.

promiseB =promiseA.then(function(result) {

  // success: dosomething and resolve promiseB

  //          with the old or a new result

  return result;

}, function(reason){

  // error: handle the error if possibleand

  //       resolve promiseB with newPromiseOrValue,

  //       otherwise forward the rejection to promiseB

  if (canHandle(reason)) {

   // handle the error and recover

   return newPromiseOrValue;

  }

  return $q.reject(reason);

});

Parameters

Param

Type

Details

reason

*

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

Returns

Promise

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

  • when(value, [successCallback], [errorCallback], [progressCallback]);

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

Parameters

Param

Type

Details

value

*

Value or a promise

successCallback

(optional)

Function=

errorCallback

(optional)

Function=

progressCallback

(optional)

Function=

Returns

Promise

Returns a promise of the passed value or promise

  • resolve(value, [successCallback], [errorCallback], [progressCallback]);

Alias of when to maintainnaming consistency with ES6.

Parameters

Param

Type

Details

value

*

Value or a promise

successCallback

(optional)

Function=

errorCallback

(optional)

Function=

progressCallback

(optional)

Function=

Returns

Promise

Returns a promise of the passed value or promise

  • all(promises);

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

Parameters

Param

Type

Details

promises

Array.<Promise>Object.<Promise>

An array or hash of promises.

Returns

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.

  • race(promises);

Returns a promise that resolves or rejects as soon as one of thosepromises resolves or rejects, with the value or reason from that promise.

Parameters

Param

Type

Details

promises

Array.<Promise>Object.<Promise>

An array or hash of promises.

Returns

Promise

a promise that resolves or rejects as soon as one of the promises resolves or rejects, with the value or reason from that promise.

相關文章
相關標籤/搜索