Let’s talk about what Promise is and what $q is first. Promise is an asynchronous processing mode, with many implementation methods, such as the famous Kris Kwal's Q and JQuery's Deffered.
What is Promise
Those who have learned about Ajax before can experience the pain of callbacks. Synchronous code is easy to debug, but asynchronous callback code will cause developers to fall into a quagmire and cannot be tracked, such as:
funA(arg1,arg2,function(){ funcB(arg1,arg2,function(){ funcC(arg1,arg2,function(){ xxxx...... }) }) }) })Nesting itself is already difficult to understand, and in addition, the callback will be triggered in some unknown time, which is equivalent to adding insult to injury.
However, with the Promise specification, it can help developers write asynchronous code in a synchronous way, such as in AngularJS:
deferABC.resolve(xxx)
.then(funcSuccess(){},funcError(){},funcNotify(){});
When the object in resolve is successfully executed, funcSuccess will be triggered, and if it fails, funcError will be triggered. A little similar
deferABC.resolve(function(){ Sunccess:funcSuccess, error:funcError, notify:funcNotify})To put it bluntly, Promise is a pre-definition of uncertain execution results. If it succeeds, it will be xxxx; if it fails, it will be xxxx, just like giving some promises in advance.
For example, Xiaobai was very lazy when he was in school. He always asked his roommate to bring food and told him in advance that if there were leeks and eggs, he would buy this vegetable, otherwise he would buy fried eggs with tomatoes; no matter if he could buy them, he should remember to bring a pack of cigarettes.
Xiaobai asked his roommate to bring meals ()
.then (leek eggs, scrambled eggs with tomatoes)
.finally (with a package of cigarettes)
$q Service
The q service is a Promise implementation implemented by itself in AngularJS, which is much lighter than Kris Kwal's Q.
Let me first introduce several commonly used methods of $q:
defer() creates a deferred object, which can execute several commonly used methods, such as resolve, reject, notify, etc.
all() passes in the array of promises, executes in batches, and returns a promise object
When() passes in an uncertain parameter, if it meets the Promise standard, it returns a promise object.
In Promise, three states are defined: waiting state, completion state, and rejection state.
There are several regulations regarding the status:
1 Changes in state are irreversible
2 The waiting state can become complete or rejected
defer() method
In $q, you can use the resolve method to become the completion state; use the reject method to become the reject state.
Let's take a look at the simple use 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 only used to test whether angularjs is normal, and has no other function 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 --- error"); 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>where 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, namely, successful callback, failed callback, and state change callback.
The variable or function passed in resolve will return the result and will be regarded as the parameter of the first then method. 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()
Let’s continue talking about the above code, then...catch... finally think of it as the try...catch... finally in java.
all() method
This all() method can combine multiple primises into one. When all promises are executed successfully, the subsequent callback will be executed. The parameters in the callback are the result of each promise execution.
This method can be used when some methods are executed 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); });Results of execution:
funcA
funcB
Array [ "hello,funA", "hello,funB" ]
When() method
When the method can be passed a parameter, which may be a value, and may be an external object that complies with the promise standard.
var funcA = function(){ console.log("funcA"); return "hello,funA"; } $q.when(funcA()) .then(function(result){ console.log(result); });This method can be used when the passed parameters are uncertain.
hello,funA
The above is a detailed introduction to the information about the Promise --- $q service in AngularJS. We will continue to add relevant information in the future. Thank you for your support for this site!