AngularJs $q promise

AngularJs $q promise

The $q service provided by angularjs is an implementation of the Promises specification. The $q service can encapsulate a piece of asynchronous code into a synchronous style. Why is it a style, because it is asynchronous or asynchronous, it does not plunge code, but looks like synchronous code. $q.when('abc').then().then(); The following code demonstrates how to use the constructor of $q. The constructor of $q accepts a function (resolve, reject), resolve is a successful return, and reject is a failed return. Usually Ajax requests are asynchronous, and the results are processed through success and failed. Through the $q service, we can rewrite this ajax request into the form of a promise. Of course, this interface is that I simulate a 2s reply ajax request through the $timeout service.

html:

<!DOCTYPE html>
<html>
    <head>
          <meta charset="UTF-8">
    </head>
    <body ng-app="app" ng-controller="ctrl">
        <style>
            .valid-error{
                color:red
            }
        </style>
        <form name="form" novalidate>
             <input type="text" ng-model="id">
             <input type="button" value="Test" ng-click='doTest()'>
        </form>
    </body>
    <script src="bower_components/angular/angular.js">
    </script>
<html>

javascript:

        var app = angular.module('app',[]);
        app.factory('dataService',function($timeout){
            var service={};
            service.persons=[{id:1,name:'Jim'},{id:2,name:'Tom'},{id:3,name:'Agile'}];
            service.getName=function(id,callback,errorCallback){
                $timeout(function(){
                    for(var i in service.persons){
                        var person = service.persons[i];
                        if(person.id==id){
                            callback(person.name);
                            return;
                        }
                    }
                    errorCallback('can not find person by id:'+id);
                },2000);
            };

            return service;
        });
        
        app.controller('ctrl',function($scope,$q,dataService){
            $scope.id='';

            function getName(id){
              return $q(function(r,j){
                  dataService.getName(id,function(data){
                      r(data);
                  },function(data){
                      j(data);
                  });
              });
            };

            $scope.doTest=function(){
               var id = $scope.id;
               getName(id).then(function(data){
                   alrt('Name is'+data);
               },function(data){
                   alrt('failed:'+data);
               });
            }

            console.log('done');

            
        });

The then method accepts 2 functions as parameters, the first is resolve and the second is reject. In fact, rewriting the ajax request into a promise does not reflect the power of $q. There is not much difference between the rewritten code and the original code.

no promise:
getName(id,function(){},function());
promise:
getName(id).then(function(){},function(){});

The promise form just mentions the two backs in the then method, but it seems to be a little more synchronized. In fact, the $http service itself is a promise realized through $q, so when you use $q to do ajax, it is already very promise.

I think the biggest benefit of $q lies in the $q.all method, which can wait for multiple promises to complete before executing the corresponding code and share it next time.

Reference: https://cloud.tencent.com/developer/article/1013425 AngularJs $q promise-Cloud + Community-Tencent Cloud