Angular学习:$q
发布日期:2021-06-29 13:10:26 浏览次数:3 分类:技术文章

本文共 11942 字,大约阅读时间需要 39 分钟。

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

$q

1.       

2.       - service in module 

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

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

This is a -compliantimplementation of promises/deferred objects inspired by .

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

$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 takesa resolver function as the first argument. Thisis similar to the native Promise implementation from ES6, see .

流线化的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的使用是仍旧可用的,并且展示在下面。

 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.

 描述了一个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 .

首先,这额外的复杂性带来的麻烦是值得的,这一点并不明显。回报来自于promise

deferred API完成的一些保证。可以参考:

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

额外的,这promise API允许合成,而这是传统的回调(CPS)方法很难完成的。更多的信息请参看 ,特别是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 ). 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  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  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 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

The newly created promise.

Methods

  • defer();

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

Returns

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

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)

errorCallback

(optional)

progressCallback

(optional)

Returns

Returns a promise of the passed value or promise

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

Alias of  to maintainnaming consistency with ES6.

Parameters

Param

Type

Details

value

Value or a promise

successCallback

(optional)

errorCallback

(optional)

progressCallback

(optional)

Returns

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

An array or hash of promises.

Returns

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

An array or hash of promises.

Returns

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

 

转载地址:https://chaiyu2002.blog.csdn.net/article/details/55504834 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:XML节点和元素的关系
下一篇:Angular学习:控制器(未翻译完)

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年04月27日 06时38分36秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

丢人不!还用System.out.println("");太 Low了! 2019-04-29
实战篇:一个核心系统 3 万多行代码的重构之旅 2019-04-29
刨根问底,Kafka消息中间件到底会不会丢消息 2019-04-29
破4!《我想进大厂》之Java基础夺命连环16问 2019-04-29
五分钟看懂抓包神技:DPDK 2019-04-29
求求你不要在用!=null判空了 2019-04-29
拒绝接口裸奔!开放API接口签名验证! 2019-04-29
放弃Maven以后,我用了它。。。 2019-04-29
程序员语言也有鄙视链!某美团程序员爆料:筛选简历时,用go语言的基本不看!网友:当韭菜还当出优越感了!... 2019-04-29
一个架构师的缓存修炼之路 2019-04-29
【JVM】肝了一周,吐血整理出这份超硬核的JVM笔记(升级版)!! 2019-04-29
工作10年,创业5年后,关于人生,我的5点思考 2019-04-29
拿下计网协议后,我就是公园里最靓的仔 2019-04-29
再见,数据库!MySQL千亿数据分库分表架构,堪称惊艳! 2019-04-29
为什么曾经优秀的人突然变得平庸? 2019-04-29
某阿里程序员求助:绩效背1,老板让他主动走!敢要n+1就在背调时说坏话!怎么办?网友:大不了鱼死网破!... 2019-04-29
知识图谱在小米的应用与探索 2019-04-29
某美团程序员爆料:美团虽然屏蔽职级,但可以通过椅子判断!坐人体工学椅的至少是3-1和3-2的大佬!真是这样吗?... 2019-04-29
图解|打工人看腾讯这道多线程面试题 2019-04-29
23张图!万字详解「链表」,从小白到大佬! 2019-04-29