$q Service In AngularJS

Background

JavaScript is a single threaded language, which means it processes code synchronously. We can archive asynchronous behavior, using callbacks. Suppose, if we have a long running task, which requires 10 seconds to complete a processing, then we can queue up this task for later, using Microtask queues (for more details, click here). This article is written for Knockout framework but is still worth reading to understand the concept of Microtask. JavaScript pulls these tasks from Microtask queue and start processing but it processes one task at a time.

Prerequisites
  • Any IDE (I used Visual Studio).
  • CDN link of Bootstrap for styling.
  • CDN link of Angular
Callbacks

Suppose, we have an Application which contains an API to do some calculation but it requires 2 minutes to do this calculation. Then, we can wait for the user to do the calculation. Alternatively, we can add some callbacks, so that when the calculation completes, it will call the callbacks passed to API.

Code snippet 

  1. function add(x, y, callback) {  
  2.     callback(x + y);  
  3. }  
  4. add(2, 6, function (result) {  
  5.     $scope.result = result;  
  6. });   

Output

Output

Let’s add some delay in the add method as I am using $timeout Angular Service.

Code snippet

  1. function add(x, y, callback) {  
  2.     $timeout(function () {  
  3.         callback(x + y);  
  4.     }, 500)  
  5. }  
  6. let startTime = Date.now();  
  7. add(2, 6, function (result) {  
  8.     $scope.result = result;  
  9.     $scope.totalTime = Date.now() - startTime;  
  10. });  

Output

Output

In the output, we can clearly see that the total time to execute the add method is 501, which means it delayed works and calculation is delayed by 500 as we set the timeout value as 500 in the $timeout Service.

So far, everything looks good and we are happy with our code but the main mess will start when we need more methods to call inside call back, which will reduce the code readability.

Code snippet 

  1. function add(x, y, callback) {  
  2.     $timeout(function () {  
  3.         callback(x + y);  
  4.     },500)  
  5. }  
  6. let startTime = Date.now();  
  7. add(2, 6, function (result) {  
  8.     add(result, 3, function () {  
  9.         $scope.result = result;  
  10.         $scope.totalTime = Date.now() - startTime;  
  11.     })  
  12. });   

Output

Output

In the code given above, we can clearly see that it takes twice the time compared to the the previous attempt and results look proper but the main concern here is the code it stated looks messy. Now, suppose if we want to handle the errors, then the code will look, as shown below.

Code snippet 

  1. function add(x, y, callback,errorCallback) {  
  2.     $timeout(function () {  
  3.         let result = x + y;  
  4.         if (result < 0)  
  5.             errorCallback("Negative error");  
  6.         else  
  7.             callback(result);  
  8.     }, 500)  
  9. }  
  10. let startTime = Date.now();  
  11. add(2, 6, function (result) {  
  12.     add(result, -13, function () {  
  13.         $scope.result = result;  
  14.         $scope.totalTime = Date.now() - startTime;  
  15.     }, function (error) {  
  16.         $scope.result = error;  
  17.         $log.error(error);  
  18.     })  
  19. }, function (error) {  
  20.     $log.error(error);  
  21. });  

Output

Output

By looking at the output, we can see that our code is working properly but the code looks messy, tough to read and understand the code.

Promise

Promise is a way of writing asynchronous coding in a better understandable way. Callback way of writing makes the code very messy as we have seen previously. We can define Promises, using $timeout, $q (angular ways) and Promises (introduced in ES 2015).

Promise using $timeout

$timeout Service of Angular returns a Promise, which we can use it to do our basic Promise example.

Code snippet 

  1. function add(x, y) {  
  2. return $timeout(function () {  
  3.     return x + y;  
  4. }, 500);  
  5.   
  6. startTime = Date.now();  
  7. 5, 2)  
  8. .then(function (result) {  
  9.     return add(result, 3);  
  10. }).then(function (result) {  
  11.     return add(result, 3);  
  12. }).then(function (result) {  
  13.     $scope.x = result;  
  14.     $scope.totalTime = Date.now() - startTime;  
  15. });   

Output

Output

The code given above runs perfectly and total time proves that add method executes 3 times due to which total time is 1520, which means more than 3 times of the time; we set in timeout. Promise makes the code readable and easy to understand than compared to Callback approach.

Promise using ES2015

In ES2015, we can implement Promise feature with an instance of Promise. This shows the importance of Promise/ Asynchronous programing that ECMA standards also defined in the standard. Let’s consider an example of Promise, using ES2015.

Code snippet 

  1. function add(x, y) {  
  2.     return new Promise(function (resolve, reject) {  
  3.         let result = x + y;  
  4.         if (result < 0) {  
  5.             reject("Negative Number");  
  6.         }  
  7.         else {  
  8.             resolve(result);  
  9.         }  
  10.     });  
  11. }  
  12.   
  13. add(1, 3).then(function (result) {  
  14.     $log.debug(result);  
  15.     return add(result, -13);  
  16. }, function (error) {  
  17.     $log.debug(error);  
  18.     
  19. })  
  20.     .then(function (result) {  
  21.         $log.debug(result);  
  22.     }, function (error) {  
  23.         $log.debug(error);  
  24.   
  25.     })   

Output

Output

Promise using $q

$q is an Angular Service, which we can use to implement deferred/ Asynchronous coding. This is a very clean and readable way of writing asynchronous way of coding and we can also add caching to handle the errors at any stage and finally to write the logic, which is supposed to be run at the end of all calls. In the example given below, we continue with the same add method, using $q Service.

First, we will execute a positive test scenario.

Code snippet 

  1. function add(x, y) {  
  2.     let q = $q.defer();  
  3.     $timeout(function () {  
  4.         let result = x + y;  
  5.         if (result < 0) {  
  6.             q.reject("Negative error");  
  7.         }  
  8.         else  
  9.             q.resolve(result);  
  10.     }, 500);  
  11.     return q.promise;  
  12. };  
  13. let startTime = Date.now();  
  14. add(5, 2)  
  15.     .then(function (result) {  
  16.         return add(result,13);  
  17.     }).then(function (result) {  
  18.         return add(result, 3);  
  19.     }).then(function (result) {  
  20.         $scope.result = result;  
  21.     }).catch(function () {  
  22.         $scope.result = "Error";  
  23.     }).finally(function () {  
  24.         $scope.totalTime = Date.now() - startTime;  
  25.     });   

Output

Output

Now, we will execute a negative scenario, which will execute the code in cache block and finally block executes in both the cases.

Code Snippet

  1. function add(x, y) {  
  2.     let q = $q.defer();  
  3.     $timeout(function () {  
  4.         let result = x + y;  
  5.         if (result < 0) {  
  6.             q.reject("Negative error");  
  7.         }  
  8.         else  
  9.             q.resolve(result);  
  10.     }, 500);  
  11.     return q.promise;  
  12. };  
  13. let startTime = Date.now();  
  14. add(5, 2)  
  15.     .then(function (result) {  
  16.         return add(result,-13);  
  17.     }).then(function (result) {  
  18.         return add(result, 3);  
  19.     }).then(function (result) {  
  20.         $scope.result = result;  
  21.     }).catch(function () {  
  22.         $scope.result = "Error";  
  23.     }).finally(function () {  
  24.         $scope.totalTime = Date.now() - startTime;  
  25.     });  

Output

Output

Conclusion

In this, we have discussed different ways of writing asynchronous code, starting from the Callback approach, which makes code messy , then using $timeout and $q (in Angular) and Promise with ES2015, using these approaches, we can have a better readable code also. We can implement caching and finally i makes our code cleaner.

References
  • http://exploringjs.com/es6/ch_promises.html#sec_introduction-promises
  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
  • https://docs.angularjs.org/api/ng/service/$q
  • https://www.w3schools.com/jquery/jquery_callback.asp

Up Next
    Ebook Download
    View all
    Learn
    View all