Angularjs promise notes

Time:2021-9-15

What is promise
Promise is a method of processing values asynchronously. Promise is an object, which represents the final possible return value or exception thrown by a function. When dealing with remote objects, we can regard it as a proxy of remote objects. If promise is also an asynchronous processing method, we will think of the difference between promise and XHR and $. Ajax?

Traditionally, JS uses closures or callbacks to respond to the data returned asynchronously, such as XHR requests after the page is loaded. We can interact with the data as if it had been returned without relying on the trigger of the callback function.

 So what is the purpose of promise proposed by ng to solve? Callbacks have been used for a long time. Usually, if a callback depends on other callbacks, debugging will become very difficult. Processing errors need to be displayed after each call. In contrast, promise provides another abstraction: these functions return promise objects.

 From a certain point of view, Ng is not simply changing the code style, but making me reflect and improve some thinking habits

Why promise

Promise is a first-class object with some conventions.

Only one resolve or reject will be called to.
If promise is executed or rejected, the handlers that depend on them will still be called.
Handlers are always called asynchronously.

To create promise in angularjs, you can use the built-in $Q service, which provides some methods in its deferred API.

angular.module('ngApp',[]).
factory('UserInfoService',['$q',function($q){
    //code here
}])

To create a deferred object, you can call the defer () method;
var deferred= $q.defer();

The deferred object exposes three methods and a promise attribute that can be used to handle promise.

resolve(value): deferred.resolve({name:”Kobe”,Age:36});
reject(reason): deferred.reject(“Can’t update user”);
notify(value)。 This method responds with the execution state of promise.  
then(successFn,errFn,notifyFn)。
catch(errFn)。
finally(callback)。 Finally allows us to observe the execution or rejection of promise without modifying the value of the result. Usually do some resource cleaning.

Let’s take a look at the object parsing of angularjs promise:

demo.html
<!DOCTYPE html>
<html ng-app="myapp">
<head>
    <title>demo</title>
</head>
<body>
    <div ng-controller="MainCtrl">{{user}}</div>
</body>
    <script type="text/javascript" src='./angular/angular.js'></script>
    <script type="text/javascript"></script>
</html>
controller.js
var myapp = angular.module('myapp', []);

myapp.factory('UserInfoService',function($http, $q) {
        return {
            query: function() {
                var defer = $q.defer();// Statement deferred execution
                $http({
                    method: 'GET',
                    URL: 'data / data. JSON' // get JSON data
                }).success(function(data, status, headers, config) {
                    defer.resolve(data);// Successful execution
                }).error(function(data, status, headers, config) {
                    defer.reject();// Execution failed
                });
                return defer.promise;// Returns the acquired data
            }
        }
    });

myapp.controller('MainCtrl',function($scope, UserInfoService){
        var promise = UserInfoService.query(); // Synchronous call to obtain the promise interface
        promise.then(function(data) {
            $scope.user = data; // Call the interface. If the data is obtained successfully, the resolve () method
        }, 

        function(data) {
            $scope.user = {
                Error: 'data was not found...' // if data acquisition fails, call reject() method
            };
        });
    });
Data to display: data.json
[{

    "id": "1",

    "firstname": "Misko",

    "lastname": "Havery",

    "company": "Google",

    "project": "AngularJS"

}, {

    "id": "2",

    "firstname": "Srini",

    "lastname": "Kusunam",

    "company": "LibertyLeap",

    "project": "Backbone.Paginator"

}, {

    "id": "3",

    "firstname": "Derick",

    "lastname": "Bailey",

    "company": "Muted Solutions",

    "project": "Backbone.Marionette"

}]

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]