Angular学习:$q

前端之家收集整理的这篇文章主要介绍了Angular学习:$q前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

$q

1.- $qProvider

2.- service in moduleng

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

一个服务,可以帮助您异步运行函数并在完成处理后使用其返回值(或异常)。

This is aPromises/A+-compliantimplementation of promises/deferred objects inspired byKris Kowal's Q.

这是Promise / A +兼容的promise / deferred对象的实现,灵感来自Kris Kowal's Q

$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.

$q可以以两种方式使用 --- 一种更类似于Kris KowalQjQueryDeferred实现,另一种在某种程度上类似于ES6ES2015)的promises

$q constructor

The streamlinedES6 style promise is essentially just using $q as a constructor which takesaresolverfunction as the first argument. Thisis similar to the native Promise implementation from ES6,seeMDN.

流线化的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 proposaldescribes 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 whattry,catchandthrowkeywords 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,seehttps://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 theQ documentationespeciallythe 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 thevalue. 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 thereason. 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 bycallingdeferred.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,thencalls 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 methodreturns a new promisewhich is resolved or rejectedvia the return value of thesuccessCallback,errorCallback(unless that value is a promise,in which case it isresolved with the value which is resolved in that promise usingpromise chaining). Italso notifies via the return value of thenotifyCallbackmethod.The promise cannot be resolved or rejected from the notifyCallback method. TheerrorCallback and notifyCallback arguments are optional.

  • catch(errorCallback)– shorthand forpromise.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 thefull specificationfor more information.

Chaining promises

Because callingthethenmethod 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.ScopeScope 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 aDeferredobjectwhich 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 specifiedreason. 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 ofrejectasthethrowkeyword 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 constructedviareject.

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 thereason.

  • when(value,[successCallback],[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,[progressCallback]);

Alias ofwhento 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 thepromisesarray/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 thepromisesresolves or rejects,with the value or reason from that promise.

原文链接:https://www.f2er.com/angularjs/148091.html

猜你在找的Angularjs相关文章