Angular--$q commitment and delay

Source: Internet
Author: User

$q

A service that helps handle asynchronous execution functions. Use their return values (or exceptions) when they are done with them.

Inspired by Kris Kowa's Q, this is an implementation of promise/deferred object enablement.

There are two ways to $q---this is a deferred implementation that is more similar to Kris Kowal Q or jquery, and another similar ES6 commitment to some extent.

Deferred Api

A new instance of the deferred that is called by $q.defer ().

The purpose of the deferred object is to expose the relevant commitment instance, as well as the success or not success of the APIs being executed, and the status of the task.

Method :

Resolve (value): Resolves the derived promise based on value. If the value is a rejection object constructed through $q.reject, the promise will be rejected.

reject (reason): Based on reason to reject the derived promise. This is done quite well by $q. Reject constructs the rejection object to solve.

Notify (value): Provides status updates during promise execution. This may be called several times before promise is resolved or rejected.

Properties :

Promise: Commitment to this delay-related commitment object.

Promise Api

When an deferred instance is created, a promise instance is created and can be retrieved by calling Deferred.promise. The purpose of the Promise object is to obtain the result of the deferred task when it is done to allow the desired place.

Method :

Then (Successcallback,errorcallback,notifycallback);

Whenever the promise is already (will) be resolved or rejected, as long as the result is available, a success/error callback is invoked asynchronously. The callback function is called with a parameter: The result of the resolution or the reason for the rejection. In addition, a notification callback may be invoked 0 or more times to provide an indication of progress before the commitment is resolved or rejected.

This method returns the return value of the resolved or rejected Successcallback/errorcallback as a new commitment (unless the return value is a promise, in the case where the commitment and value of the commitment chain are resolved). It will also be notified by the return value of the Notifycallback method. Promise cannot be resolved or rejected from the Notifycallback method.

catch (Errorcallback);

A shortcut to Promise.then (null, errorcallback).

Finally (Callback,notifycallback);

Allows you to observe a promise of resolution or rejection, but doing so does not modify the last value. This can be used for promise either to release resources or do some cleanup after being resolved or rejected.

Chain Commitment

Because calling this promise method will return a new deferred promise, it is easy to create a commitment chain:

  Promise = Promise.then (function (result) {  return  result+1;  }); 

When a commitment resolves another promise (which will postpone its further resolution), it may create a chain of any length. It may suspend/postpone the commitment at any point in the chain. This makes it possible to intercept such powerful APIs like $http's response.

Kris Kowal ' s Q and $q are different

The following are the two main differences:

In angular, the observation mechanism of the $q and $rootscope.scope Scope model is integrated, which means that the results of resolution/rejection are propagated faster to your model and avoid unnecessary browser re-rendering (which will cause the UI to blink).

Q has more features than $q, but this is at the cost of bytes. $q is a small version, but contains all the features that are important for all common asynchronous tasks.

Dependency : $rootScope

Use : $q (resolver);

Method :

Defer ();

Creates a deferred object that represents a task that will be completed in the future. Returns a new instance of a deferred.

Reject (reason);

Creates a commitment that is rejected by the specified reason. In the commitment chain, this API will be used to commit the rejection. If you are dealing with the last promise of a commitment chain, then you don't need to worry about it.

Reason: Constant, message, exception, or an object that represents the reason for the rejection.

Returns a commitment that has been resolved based on the reason for the rejection.

When (value);

Commit an object or a value or a third party commitment to $q. When you deal with an object that may be a promise or may not be a promise or promise from an untrusted source.

Value: values or commitments.

Return a promise.

Resolve (value);

When alias, in order to be consistent with ES6.

All (promises);

When all commitments are resolved, a single commitment is made to assemble multiple resolved commitments.

Promises: A committed array or hash.

Returns a single commitment that will be combined with an array/hash or value resolution, each value in the same index/key array/Hash commitment corresponds to a relative commitment, and if any commitment is rejected, this will cause the commitment to be rejected with the same deny value.

Using code:

(function() {angular.module (' Demo ', []). Controller (' Testctrl ', ["$q", Testctrl]);functionTestctrl ($q) {var fn =function(value) {var defer =$q. Defer ();if (value = = "Hello"{Defer.resolve ("Hello World")); }Else{defer.reject ("Hello World"); }ReturnDefer.promise; };var promise = fn ("Hello"); Promise.then (function V); }, function R); }); //var Anotherpromise = FN (); Anotherpromise.then (function< Span style= "color: #000000;" > (v) {Console.log ("Resolved with" +function (R) {Console.log ("Rejected with" + r);}); //hello world  

Commitment chain :

(function() {angular.module (' Demo ', []). Controller (' Testctrl ', ["$q", Testctrl]);functionTestctrl ($q) {var FnA =function(value) {var defer =$q. Defer ();if (value = = "Hello"{Defer.resolve ("Hello World-FnA")); }Else{defer.reject ("Hello World-FnA")); }ReturnDefer.promise; };var FnB =function(value) {var defer =$q. Defer ();if (value = = "Hello"{Defer.resolve ("Hello World--FnB")); }Else{defer.reject ("Hello World--FnB")); }ReturnDefer.promise; };var promise = FnA ("Hello"); Promise.then (function (v) {Console.log (" resolved with "+ V); hello world--FnA return  FnB ();}, function (R) { Console.log ("Rejected with" + R); return FnB ("Hello" function (v) {Console.log ("Resolved with" + V); }, function//hello world--Fnb    

. When ():

(function() {angular.module (' Demo 'function Testctrl ($q) { var obj = {value: "Hello World" ", $q. When (Obj.value). Then (function// Hello World obj = {text: "Hello World" } return $q. when (Obj.text);}). Then (function// hello World     

. All ():

(function() {angular.module (' Demo ', []). Controller (' Testctrl ', ["$q", Testctrl]);functionTestctrl ($q) {var FnA =function(value) {var defer =$q. Defer ();if (value = = "Hello"{Defer.resolve ("Hello World-FnA")); }Else{defer.reject ("Hello World-FnA")); }ReturnDefer.promise; };var FnB =function(value) {var defer =$q. Defer ();if (value = = "Hello"{Defer.resolve ("Hello World--FnB")); }Else{defer.reject ("Hello World--FnB")); }ReturnDefer.promise; };var Promisea = FnA ("Hello"). Then (function(v) {Console.log ("Resolved with" +V);ReturnFnB (); },functionreturn FnB ("Hello" var promiseb = FnB (). Then (function (v) {Console.log ("Resolved with" +function (R) {Console.log ("Rejected with" + r);}); var promises = [Promisea, Promiseb]; $q. All (promises); Span style= "color: #008000;" >/* result: * * Resolved with Hello world-fnA * * Rejected with Hello world-FnB */           

About $q, the beast at present understanding of these, with the words also look at the situation with, more often think it is like a grammar sugar, just save more than n nested, but have to say that this syntax sugar to make the code readability and cleanliness of a lot better. But the beast feels that $q more benefits in promise and deferred, creating a commitment to come back to address this commitment in the areas that are needed later. Also recommended a description of $q article, the Snow Wolf Uncle wrote, the URL is: http://www.ngnice.com/posts/126ee9cf6ddb68

Angular--$q commitment and delay

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.