Promise in Angular
When using jQuery, I knew that promise is a mode of Js asynchronous programming mode, but I didn't understand the difference between it and JQuery's deferred object. As the company's project progresses, we have to receive data from the backend, so we decided to get it done.
Promise
Promise is a mode that operates asynchronous events in the form of synchronous operations, avoiding layer by layer of nesting, and can operate asynchronous events in chains.
We know that when writing JavaScript asynchronous code, callback is the easiest mechanism, but if you use this mechanism, you must sacrifice control flow, exception handling and function semantics, and even let us fall into a callback pit, and promise solves this problem.
In ES6, the built-in AngularJS built-in Q in AngularJS, and when they use the Promises/A specifications, as follows:
Each task has three states: pending, fulfilled, and failed.
- pending state: can be transitioned to fulfillment or rejection state.
- fulfilled state: cannot be changed to any other state, and the state cannot be changed, and must have a value value.
- rejected state: cannot be changed to any other state, and the state cannot be changed, there must be a reason.
The transfer of state is one-time. Once the state becomes fulfilled (completed) or failed (failed/rejected), it cannot change any more.
function okToGreet(name){ return name === 'Robin Hood'; } function asyncGreet(name) { var deferred = $(); setTimeout(function() { // Because this asynchronous function fn is executed in the future asynchronously, we wrap the code into the $apply call, and correctly observe the change in the model $scope.$apply(function() { ('About to greet ' + name + '.'); if (okToGreet(name)) { ('Hello, ' + name + '!'); } else { ('Greeting ' + name + ' is not allowed.'); } }); }, 1000); return ; } var promise = asyncGreet('Robin Hood'); (function(greeting) { alert('Success: ' + greeting); }, function(reason) { alert('Failed: ' + reason); }, function(update) { alert('Got notification: ' + update); });
Q Basic usage of Promise
The above code shows the role of several methods of the deffered instance built by $(). If the asynchronous operation is successful, the state of the Promise object is changed to "success" (i.e., from pending to resolved); if the asynchronous operation is failed, the state is changed to "failed" (i.e., from pending to rejected). Finally, we can call the then method in a chain.
JS will have native Promise, there are already Promise objects in ES6, and the basic Promise API is implemented in firefox and Chrome 32 beta versions.
$ in AngularJs
Returns the deffered object by calling $ in chained form. This object associates the three task states in the Promises/A specification through the API.
deffered API
Method of deferred object
- resolve(value): At the declaration resolve(), it indicates that the promise object has changed from the pending state to resolve.
- reject(reason): At the declaration resolve(), it indicates that the promise object has changed from the pending state to rejected.
- notify(value): At the declaration notify(), it indicates that the promise object is unfulfilled and can be called multiple times before resolving or rejecting.
deffered object properties
promise: The last thing that returns is a new deferred object promise property, not the original deferred object. This new Promise object can only observe the status of the original Promise object, and cannot modify the internal state of the deferred object, which can prevent the task state from being modified externally.
Promise API
When creating a deferred instance, a new promise object is created and the reference can be obtained through .
The purpose of the promise object is to allow the interested part to obtain its execution results when the deferred task is completed.
Methods of promise objects
then(errorHandler, fulfilledHandler, progressHandler): then method is used to listen for different states of a Promise. The errorHandler listens to failed state, the fulfilledHandler listens to fulfilled state, and the progressHandler listens to unfulfilled state. Additionally, the notify callback may be called 0 to multiple times, providing a progress indication before resolving or rejecting (resolving and rejecting).
catch(errorCallback) —— (null, errorCallback) shortcut
finally(callback) - allows you to observe whether a promise is executed or rejected, but do not need to modify the last value. This can be used to free resources or clean up useless objects, regardless of whether the promise is rejected or resolved. For more information, see the full documentation specification.
Promise chain call can be implemented through the then() method.
promiseB = (function(result) { return result + 1; }); // promiseB will be processed immediately after the promiseA is processed.// and its value value is promiseA's result is increased by 1
Other methods of $q
- $(value): Pass the variable value, () executes a successful callback
- $(promises): Multiple promises must be executed successfully before they can be executed successfully. The value is passed as an array or hash value. Each value in the array is corresponding to the Index.
promise object.
angular $apply ->Successful response
angular http request intercept
Thank you for reading, I hope it can help you. Thank you for your support for this site!