English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Let's talk about what Promise is first, and what $q is. Promise is an asynchronous processing pattern with many implementation methods, such as the famous Kris Kwal's Q and jQuery's Deffered.
What is Promise
Those who have ever understood Ajax can feel the pain of callbacks. Synchronous code is easy to debug, but asynchronous callback code can trap developers in a quagmire, making it impossible to track, for example:
funA(arg1,arg2,function(){ funcB(arg1,arg2,function(){ funcC(arg1,arg2,function(){ xxxx.... }) }) })
The nested structure is already not easy to understand, and with the uncertainty of when the callback will be triggered, it's like adding salt to the wound.
However, with the Promise specification, it can help developers write asynchronous code in a synchronous way, such as using this method in AngularJS:
deferABC.resolve(xxx)
.then(funcSuccess(){}, funcError(){}, funcNotify(){});
When the object inside resolve is successfully executed, it will trigger funcSuccess, and if it fails, it will trigger funcError. It is somewhat similar to
deferABC.resolve(function(){ Sunccess:funcSuccess, error:funcError, notify:funcNotify })
To put it more directly, Promise is a predefined for an uncertain execution result, if successful, then xxxx; if failed, then xxxx, just like giving some promises in advance.
For example, Xiao Bai was very lazy when he was studying, and he always asked his roommate to bring him food. He had also agreed in advance that if there was leek and egg, he would buy this dish, otherwise he would buy stir-fried egg with tomato. No matter whether he could buy it or not, he had to remember to bring a pack of cigarettes.
Xiao Bai asks his roommate to bring him food()
.then(drumstick and egg, stir-fried egg with tomato)
.finally(smoking with a cigarette)
$q service
The q service is a Promise implementation encapsulated by AngularJS itself, which is much lighter than Kris Kwal's Q.
First, let's introduce several commonly used methods of $q:
defer() creates a deferred object, which can execute several common methods, such as resolve, reject, notify, etc.
all() passes an array of Promises, executes in batches, and returns a promise object
When() passes an uncertain parameter, if it meets the Promise standard, it returns a promise object.
In Promise, three states are defined: pending state, resolved state, and rejected state.
There are several rules about the state:
1 State changes are irreversible
2 The pending state can become resolved or rejected
defer() method
In $q, you can use the resolve method to become a resolved state; use the reject method to become a rejected state.
Let's take a look at the simple usage of $q:
<html ng-app="myApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script> </head> <body> <div ng-controller="myctrl"> {{test}} </div> <script type="text/javascript"> var myAppModule = angular.module("myApp",[]); myAppModule.controller("myctrl",["$scope","$q",function($scope, $ q ){ $scope.test = 1;//This is just to test if angularjs is working normally, with no other purpose var defer1 = $q.defer(); var promise1 = defer1.promise; promise1 .then(function(value){ console.log("in promise1 ---- success"); console.log(value); },function(value){ console.log("in promise1 ---- error"); console.log(value); },function(value){ console.log("in promise1 ---- notify"); console.log(value); }) .catch(function(e){ console.log("in promise1 ---- catch"); console.log(e); }) .finally(function(value){ console.log('in promise1 ---- finally'); console.log(value); }); defer1.resolve("hello"); // defer1.reject("sorry, reject"); }); </script> </body> </html>
defer() is used to create a deferred object, defer.promise is used to return a promise object to define the then method. There are three parameters in then, which are the success callback, failure callback, and state change callback.
The variable or function return result passed to resolve will be used as the parameter of the first then method. The then method returns a promise object, so it can be written as
xxxx
.then(a, b, c)
.then(a, b, c)
.then(a, b, c)
.catch()
.finally()
Continue to talk about the above code, then...catch...finally can be thought of as try...catch...finally in Java.
all() method
This all() method can combine multiple promise arrays into one. After all the promises are executed successfully, the callback after will be executed. The parameters in the callback are the results of each promise execution.
You can use this method when executing certain methods in batches.
var funcA = function(){ console.log("funcA"); return "hello,funA"; } var funcB = function(){ console.log("funcB"); return "hello,funB"; } $q.all([funcA(),funcB()]) .then(function(result){ console.log(result); });
Execution result:
funcA
funcB
Array [ "hello,funA", "hello,funB" ]
when() method
You can pass a parameter into the when method, which may be a value or an external object that conforms to the promise standard.
var funcA = function(){ console.log("funcA"); return "hello,funA"; } $q.when(funcA()) .then(function(result){ console.log(result); });
You can use this method when the parameters passed in are uncertain.
hello,funA
The above is the explanation of Promise in AngularJS --- Detailed introduction of the $q service, we will continue to supplement relevant information, thank you all for your support to this site!
Declaration: The content of this article is from the network, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, does not undergo manual editing, and does not bear relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)