The promise in the angular
When you use jquery, you know promise is a pattern of JS asynchronous Programming mode, but it's not quite clear what difference he has with jquery's deferred object. With the company project, to the background with the data, so decided to fix it.
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.
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 changes $scope the model
. $apply (Function ( {
deferred.notify (' About to greet ' + name + '. ');
if (Oktogreet (name)) {
deferred.resolve (' Hello, ' + name + '! ');
} else {
deferred.reject (' greeting ' + nam E + ' 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).
Shortcut to catch (errorcallback)--promise.then (null, Errorcallback)
Finally (callback)-lets you observe whether a promise is executed or rejected, but does not modify the final 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 the implementation of promise chained calls.
PROMISEB = Promisea.then (function (result) {return result
+ 1;
});
The PROMISEB will be processed immediately after the Promisea is processed,
//And the value of the Promisea 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, passing an array or hash value, each of which corresponds to the index
Promise object.
Angular $apply-> Successful response
Angular HTTP request interception
Thank you for reading, I hope to help you, thank you for your support for this site!