Deep analysis of Promise objects in Angularjs ($q

Source: Internet
Author: User
Tags exception handling


What's Angularjs?



Angularjs was born in 2009, by Misko Hevery and other people to create, after the acquisition of Google. is an excellent front-end JS framework, has been used in a variety of Google products. Angularjs has many characteristics, the most core is: MVVM, modular, automated two-way data binding, semantic tagging, dependency injection, and so on



Promise



Promise is a mode in which asynchronous events are manipulated in the form of a synchronous operation, avoiding layers of nesting and chaining operations to asynchronous events.



We know that when writing JavaScript asynchronous code, callback is the simplest mechanism, but it has to sacrifice control flow, exception handling and function semantics to the cost, and even let us fall into the callback pit, and promise solve the problem.



ES6 Promise, Angularjs built-in Q, and when used are promises/a specifications, as follows:



There are three states of each task: incomplete (pending), complete (fulfilled), failure (rejected).



Pending state: A transition to a performance or deny state.
Fulfilled state: cannot be changed to any other state, and the state cannot change, and must have a value.
Rejected state: cannot be changed to any other state, and the state cannot change, there must be reason.
The transfer of state is one-off, and once the state becomes fulfilled (completed) or failed (failure/rejection), it cannot be changed again.


The code is as follows

function Oktogreet (name) {
return name = = ' Robin Hood ';
}

function Asyncgreet (name) {
var deferred = $q. Defer ();

settimeout (function () {
Because this asynchronous function FN executes in the future asynchronously, we wrap the code into the $apply call and observe the model changes correctly.
$scope. $apply (function () {
Deferred.notify (' About to greet ' + name + '. ');

if (Oktogreet (name)) {
Deferred.resolve (' Hello, ' + name + '! ');
} else {
Deferred.reject (' greeting ' + name + ' is not allowed. ');
}
});
}, 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);
});


The basic usage of Q promise



The code above indicates the role of several methods of the deffered instance constructed by $q. Defer (). If the asynchronous operation succeeds, the state of the Promise object is changed to success (that is, from pending to resolved) by using the Resolve method, and if the asynchronous operation fails, the state is changed to "failed" (that is, from reject to pending). Finally, returning deferred.promise, we can call the then method by chain.



JS will have native PROMISE,ES6 already have promise objects, Firefox and Chrome beta version has implemented the basic promise API



The $q.defferd in the Angularjs



Returns the Deffered object as a chained call by calling $q. Defferd. This object associates the three task states in the PROMISES/A specification with the API.



Deffered API



Methods of Deffered Objects



Resolve (value): At the Declaration resolve (), the Promise object is converted from pending state to resolve.
Reject (reason): at the Declaration resolve (), the Promise object is converted from the pending state to rejected.
Notify (value): At the Declaration notify (), indicates that the promise object unfulfilled state, can be invoked multiple times before resolve or reject.
Deffered Object Properties



Promise: The final return is a new deferred object Promise property, not the original deferred object. This new promise object can only observe the state of the original promise object, but cannot modify the internal state of the deferred object to prevent the task State from being externally modified.



Promise API



When a deferred instance is created, a new Promise object is created, and the reference can be obtained by deferred.promise.



The purpose of the Promise object is to allow the interested part to obtain its execution results when the deferred task completes.



Methods of Promise Objects



Then (ErrorHandler, Fulfilledhandler, Progresshandler): The then method is used to monitor the different states of a promise. ErrorHandler Monitor failed state, Fulfilledhandler Monitor fulfilled status, Progresshandler monitor unfulfilled (unfinished) state. In addition, the notify callback may be invoked 0 to several times, providing a progress indication before resolving or rejecting (resolve and rejected).
catch (errorcallback)--promise.then (null, errorcallback) Shortcuts
Finally (callback)--so you can observe a promise is executed or rejected, but doing so does not change the last value. This can be used to do some of the work of releasing resources or cleaning up unwanted objects, whether promise is rejected or resolved. For more information, see the full documentation specification. The
Then () method enables promise chained calls.


The code is as follows

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

PROMISEB will be processed immediately after the Promisea is processed,
And its value is promisea and the result is increased by 1.


Other ways to $q



$q. When (value): Passing variable values, Promise.then () executing a successful callback
$q. All (promises): Multiple promise must perform successfully in order to perform a successful callback, pass the value as an array or hash value, and each value in the array is the Promise object corresponding to the index.


Related Article

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.