Describe
Translator Note : see a very good article, if you are interested, you can view: Promises and JavaScript asynchronous programming, the inside of the promises specification and use of the situation, the benefits speak very well, personally feel easy to understand.
Since it is used to deal with asynchronous programming, in the browser-side JS, the main is 2 kinds: setTimeout and AJAX requests. The use of promise is much like the success and failure callbacks of Ajax requests.
This commitment/delay (promise/deferred) implementation is inspired by the Kris Kowal's Q CommonJS promise suggests that the document will commit (promise) as an interface for interacting with the Asynchronous execution action (action) Result object. May or may not be completed within the specified time (e.g. timeouts, errors, interception, etc.).
From the point of view of error handling, the delay (deferred) and Commitment (PromiseAPI for asynchronous programming, and synchronous programming try,catch, as well as the throw effect is similar.
[JavaScript]View PlainCopy
- For the purposes of the demonstration, here we assume that ' $q ', ' scope ', and ' Oktogreet ' references are available in the current execution environment
- (for example, they have been injected, or have been passed in as parameters).
- function Asyncgreet (name) {
- var deferred = $q. Defer ();
- SetTimeout (function () {
- //Because this function executes asynchronously in a future event loop,
- //We need to wrap the code into a $apply call in order to properly observe the model change
- Scope. $apply (function () {
- Deferred.notify (' upcoming greetings ' + name + '. ');
- if (oktogreet (name)) {
- Deferred.resolve (' Hello, ' + name + '! ');
- } Else {
- Deferred.reject (' refuse greeting ' + name + '. ');
- }
- });
- }, 1000);
- return deferred.promise;
- }
- var promise = Asyncgreet (' small Misty ');
- Promise.then (function (greeting) {
- Alert (' success: ' + greeting);
- }, function (reason) {
- Alert (' failed bird: ' + reason ');
- }, function (update) {
- Alert (' receive notification: ' + update ');
- });
The effect of attracting this extra complexity may not be apparent at first. When it comes to the promise of promise and deferred APIs, see: Https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md
In addition, the Promise API allows for combinations of implementations that are difficult to implement in traditional callback (CPS) methods. For more information, please refer toQ Documentation, especially in the serial and parallel merge section.
Delay Interface | The Deferred API can build a new deffered instance by calling the $q. Defer ().
The Deffered object is used to associate an Promise instance with an API that marks the status of the task, either successfully or unsuccessfully.
Methods for Deffered objects
- Resolve (value)--Incoming value resolves the derived promise. If value is a Deny object (rejection) that is constructed by $q. Reject, the promise will be rejected.
- Reject (reason)--rejects the derived promise and provides the reason. This is equivalent to passing the $q. Reject constructed Deny object (rejection) as a parameter to resolve.
- Notify (value)-Provides a status update during promise execution. This may be called several times before the promise is resolved or rejected.
The property of the Deffered object promise–{promise}--the Promise object associated with the delay (deferred).
Commitment Interface | Promise API When you create a deferred instance, a new Promise object is created, and you can get the reference by Deferred.promise.
The purpose of the Promise object is to allow the part of interest to get its execution results when the deferred task completes.
Methods for Promise Objects
- Then (Successcallback, Errorcallback, Notifycallback)--whether the promise is handled or rejected, once the result is available, then the success/error callback function is called asynchronously as soon as the result is available. Pass a single argument when invoking a callback function: The reason for the result or rejection. Additionally, the notify callback may be called 0 to multiple times to provide a progress indication before the commitment is resolved or rejected.
This method returns a new promise object that is resolved or rejected according to Successcallback, Errorcallback's return value. It is also notified by the return value of the Notifycallback method. Promise cannot be resolved or rejected from the Notifycallback method.
- catch (Errorcallback)--promise.then (NULL, errorcallback) shortcut
- Finally (callback)--allows you to see whether a promise is being executed or rejected, but does not modify the last value value. This can be used to do work that frees up resources or cleans up useless objects, whether promise is rejected or resolved. For more information, see the full documentation specification.
Because finally is a reserved word keyword in the ES3 version of JavaScript and cannot be used as a property name, you need to call this method in the form of promise[' finally ' (callback) in order to fit the IE8.
Promise Chain | Chaining promises because calling a promise then method returns a new derived promise instance, it is also easy to build the promises chain:
[JavaScript]View PlainCopy
- Promiseb = Promisea.then (function (result) {
- return result + 1;
- });
- PROMISEB will be processed immediately after the Promisea has been processed,
- and its value value is Promisea's result increases by 1
We can create promise chains of any length, because one promise can be processed by another promises (further delaying the completion time), so it is possible to pause/postpone the resolution at any point on the promise chain. This makes implementing powerful APIs a reality, such as $http response interceptors.
The main difference between Kris Kowal's Q and $q is two points:
- The $q in angular integrates ng. $rootScope. Scope scope model observation mechanism, which means that the resolution or rejection of the models will be faster, avoiding unnecessary browser repainting (which can cause UI flicker).
- Q has more features than $q, but it does increase the number of code bytes. $q is lightweight, but contains all the important features that are required for general asynchronous tasks.
Test[JavaScript]View PlainCopy
- It (' should simulate promise ', inject (function ($q, $rootScope) {
- var deferred = $q. Defer ();
- var promise = Deferred.promise;
- var resolvedvalue;
- Promise.then (function (value) {resolvedvalue = value;});
- Expect (Resolvedvalue). tobeundefined ();
- //Analog Promise's resolving
- Deferred.resolve (123);
- //Note that the ' then ' function is not called synchronously.
- //Because we want the promise API to always be asynchronous (async),
- This is true both in synchronous and asynchronous calls.
- Expect (Resolvedvalue). tobeundefined ();
- //Use $apply () to pass promise resolution to ' then ' functions.
- $rootScope. $apply ();
- Expect (Resolvedvalue). Toequal (123);
- }));
Dependency Relationships | Dependencies$rootScope
Method | MethodsAll (promises)Combined with multiple promises for a single promise, after all input promise are processed, the combined promise is processed.
- Parameter: Promises
- Type: array.<promise>/object.<promise>
- Description: An array of promises or references
- Returns: Promise returns a single Promise that will be resolved with an array/hash value, each value corresponding to the same index/key commitment/hash array. If any commitment resolves the exclusion, the resulting promise will be rejected with the same value.
Defer () Creates a deferred object that represents a future completion task.
- Returns a Deferred that returns a new instance of Deferred.
Reject (reason) creates a promise that specifies the reason for the rejection. This API should be used to reject in a promises chain. If you're dealing with the last promise in the promise chain, you don't need to worry.
By comparing deferreds/promises with our familiar try/catch/throw behavior, you can think of reject equivalent to the throw keyword in JavaScript. This also means that if you pass a promise error callback and "Catch" a mistake, you want to indicate that the current commit has been executed in error, you must re-throw a "reject with the error message and reject it".
[JavaScript]View PlainCopy
- Promiseb = Promisea.then (function (result) {
- ///success: You can perform certain operations here, and then use the original result directly,
- //or manipulate the result to handle the next Promiseb
- return result;
- }, function (reason) {
- //Error:handle the error if possible and
- //Resolve PROMISEB with Newpromiseorvalue,
- //Otherwise turn to reject PROMISEB branch
- if (canhandle (reason)) {
- //Handling errors and recoveries
- return newpromiseorvalue;
- }
- return $q. Reject (reason);
- });
- Parameter: Reason
- Type: *
- Description: Constant, message, exception, or object representing the reason for rejection.
- Return: Promise Returns a Promise that has been rejected for reason.
When (value) wraps an object (possibly value or [third-party]then-able promise) as a $q promise. This is useful when you are unsure whether the object being handled is a promise, and it is possible that the object is from a source that is not trusted.
- Parameters: Value
- Type: *
- Description: Value of Promise
- Returns Promise returns a wrapped Promise based on the value passed in/or Promise
$Q-Services in Angularjs (understanding)