Service $ q in angularJS

                     Reprinted from http://blog.csdn.net/renfufei/article/details/19174015

description

Translator's Note : I saw a very good article, if you are interested, you can check:  Promises and Javascript asynchronous programming  , which contains Promises specifications and usage scenarios, the benefits are very well explained, personally feel simple and easy to understand.

Since it is used to handle asynchronous programming, there are two main types of JS in the browser: setTimeout and Ajax requests. The use of promises is very similar to the success and failure callbacks of Ajax requests.


This promise / deferred implementation is inspired by   Kris Kowal's Q CommonJS Promise recommendation document that  uses promises as an interface to interact with asynchronous execution result objects, which may be completed within a specified time or possible Unable to complete (such as timeout, error, interception, etc.).

From the perspective of error handling, deferred  and promise  APIs are similar to  try , catch , and throw in  synchronous programming for asynchronous programming .
[javascript]  view plain  copy
  1. // For demonstration purposes, here we assume that `$ q`,` scope` and `okToGreet` references are available in the current execution environment  
  2. // (For example, they have been injected or passed in as parameters).  
  3.    
  4. function asyncGreet(name) {  
  5.   var deferred = $q.defer();  
  6.    
  7.   setTimeout(function() {  
  8.     // Because this function is executed asynchronously in the future event loop,  
  9.     // We need to wrap the code into a $ apply call in order to correctly observe the model change  
  10.     scope.$apply(function() {  
  11.       deferred.notify ( 'greeting soon'  + name +  '.' );  
  12.    
  13.       if (okToGreet(name)) {  
  14.         deferred.resolve ( 'Hello,'  + name +  '!' );  
  15.       } else {  
  16.         deferred.reject ( 'Reject greeting'  + name +  '.' );  
  17.       }  
  18.     });  
  19.   }, 1000);  
  20.    
  21.   return deferred.promise;  
  22. }  
  23.    
  24. var  promise = asyncGreet ( 'Little desert' );  
  25. promise.then(function(greeting) {  
  26.   alert ( 'Success:'  + greeting);  
  27. }, function(reason) {  
  28.   alert ( 'Failed bird:'  + reason);  
  29. }, function(update) {  
  30.   alert ( 'Received notification:'  + update);  
  31. });  

The effect of introducing this extra complexity may not be obvious at first. The benefits are seen when promises and deferred APIs are committed, please refer to:   https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md
In addition, the promise api allows those in traditional callbacks (CPS) A combination that is difficult to achieve in the method. For more information, please refer to the  Q documentation  , especially the section on Merging Serial and Parallel.

Delay Interface | Deferred API

通过调用  $q.defer() 可以构建一个新的 deffered 实例。
deffered 对象用来将 Promise 实例与 标记任务状态(执行成功还是不成功)的 API 相关联。

deffered 对象的方法

  • resolve(value) ——传入 value 解决派生的 promise。 如果 value 是一个通过 $q.reject 构造的拒绝对象(rejection) , 该promise 将被拒绝。
  • reject(reason) ——拒绝派生的promise,并提供原因 。 这相当于通过 $q.reject构造的拒绝对象(rejection)作为参数传递给 resolve。
  • notify(value)  ——在 promise 执行的过程中提供状态更新。 这在 promise 被解决或拒绝之前可能会被多次调用。

deffered 对象的属性

promise – {Promise}  —— 与延迟(deferred)相关联的 promise 对象。

承诺 接口 | Promise API

当创建 deferred 实例时会创建一个新的 promise 对象,并可以通过   deferred.promise  得到该引用。
promise 对象的目的是在 deferred 任务完成时,允许感兴趣的部分取得其执行结果。

promise 对象的方法

  • then(successCallback, errorCallback, notifyCallback) ——不管 promise 是被处理还是被拒绝, 一旦结果可用,then 就会尽快地异步调用 成功/错误 回调函数 只要结果是可用的。 调用回调函数时传递单个参数: 结果 或拒绝的理由。 此外,notify 回调可能被调用 0到多次,以提供 提供一个进度指示,之前承诺解决或拒绝。
           这个方法 返回一个新的promise 对象, 根据 successCallback , errorCallback的返回值进行解决或拒绝 。 它还通过 notifyCallback 方法的返回值进行通知。 promise 不能从notifyCallback方法得到解决或拒绝 。
  • catch(errorCallback) —— promise.then(null, errorCallback) 的快捷方式
  • finally(callback) ——让你可以观察到一个 promise 是被执行还是被拒绝, 但这样做不用修改最后的 value值。 这可以用来做一些释放资源或者清理无用对象的工作,不管promise 被拒绝还是解决。 更多的信息请参阅完整文档规范.
            因为在 ES3版本的JavaScript中 finally 是一个保留字关键字,不能作为属性名,为了适配 IE8,您需要使用  promise['finally'](callback) 这种形式来调用该方法。

promise 链 | Chaining promises

因为调用一个 promise 的 then 方法返回一个新的派生 promise实例,所以构建promises链也是很容易的:
[javascript]  view plain  copy
  1. promiseB = promiseA.then(function(result) {  
  2.   return result + 1;  
  3. });  
  4.    
  5. // promiseB 将会在处理完 promiseA 之后立刻被处理,  
  6. // 并且其  value值是promiseA的结果增加1  
我们可以创建任意长度的promise链;因为一个promise可以被另一个promises处理(进一步推迟解决完成时间),所以在promise链上的任意一点进行 暂停/推迟解决 都是可行的。 这使得实现功能强大的APIs 成为现实,例如   $http  的响应拦截器。

Kris Kowal's Q 与 $q 之间的区别

主要区别有两点:
  • Angular中的$q 集成了 ng.$rootScope.Scope  Scope模型观察机制,这意味着对models 的解决或拒绝速度将会更快,避免不必要的浏览器重绘(会导致UI闪烁)。
  • Q 比 $q拥有更多的功能特性,但带来的是代码字节数的增加。 $q 很轻量级,但包含了一般异步任务所需的所有重要功能。

     测试

[javascript]  view plain  copy
  1. it('should simulate promise', inject(function($q, $rootScope) {  
  2.   var deferred = $q.defer();  
  3.   var promise = deferred.promise;  
  4.   var resolvedValue;  
  5.    
  6.   promise.then(function(value) { resolvedValue = value; });  
  7.   expect(resolvedValue).toBeUndefined();  
  8.    
  9.   // 模拟 promise 的 resolving  
  10.   deferred.resolve(123);  
  11.   // 注意 'then' function 不是同步调用的.  
  12.   // 因为我们想要  promise API 一直是异步的(async),  
  13.   // 不管是在同步调用还是异步调用中都是如此.  
  14.   expect(resolvedValue).toBeUndefined();  
  15.    
  16.   // 使用 $apply()将 promise resolution 传递到 'then' functions .  
  17.   $rootScope.$apply();  
  18.   expect(resolvedValue).toEqual(123);  
  19. }));  

依赖关系 | Dependencies

$rootScope 

方法 | Methods

all(promises)

结合多个promises为单个promise,在所有输入的promise都处理之后,组合之后的promise才会处理完成。
  • 参数: promises
  • 类型: Array.<Promise>/Object.<Promise>
  • 描述: promises的数组或者引用
  • 返回: Promise 返回单个的 promise,将与一个数组解决/散列值, 每个值对应于在相同的索引/关键的承诺 承诺 /散列数组。 如果任何承诺解决排斥,这产生的承诺将被拒绝 拒绝相同的值。

defer()

创建一个 递延 对象代表一个将来完成任务。
  • 返回  Deferred 返回一个新实例的Deferred。

reject(reason)

创建一个指定拒绝原因的promise. 此api应该用于在一个promises链中进行拒绝。 如果你正在处理promise 链中的最后一个promise,你不需要担心。

把  deferreds/promises 与我们熟悉的的 try/catch/throw行为进行对比,可以认为 reject 相当于 JavaScript 中的throw 关键字。 这也意味着如果你通过一个 promise 的 error回调,  “catch”了一个错误 ,你想要指明当前的承诺已经执行出错了,就必须重新抛出一个“附带了错误信息,拒绝通过的reject” 。
[javascript]  view plain  copy
  1. promiseB = promiseA.then(function(result) {  
  2.   // success: 此处可以执行某些操作,然后直接使用原有的result,  
  3.   // 或者对result进行操作,来处理接下来的promiseB  
  4.   return result;  
  5. }, function(reason) {  
  6.   // error: handle the error if possible and  
  7.   //        resolve promiseB with newPromiseOrValue,  
  8.   //        否则转向拒绝 promiseB 的分支  
  9.   if (canHandle(reason)) {  
  10.    // 处理错误和恢复  
  11.    return newPromiseOrValue;  
  12.   }  
  13.   return $q.reject(reason);  
  14. });  
  • Parameter:  reason
  • Types of: *
  • Description:  Constant, message, exception  or object representing the reason for rejection.
  • Return:  Promise     returned a promise, which has been rejected because of reason.

when(value)

Wrap an object (probably value or [third-party] then-able promise) into a $ q promise. This is useful when you are not sure whether the object being processed is a promise. It is possible that the object comes from an untrusted source.
  • Parameter:  value
  • Types of: *
  • Description: The value of the promise
  • Return  Promise     returns a wrapped promise based on the passed value / or promise



Published 7 original articles · won 5 · visited 4120

Guess you like

Origin blog.csdn.net/blue_heart_/article/details/78772539