AngularJS $q and $q. All single data sources and multiple data sources merging (Promise's description)

Source: Internet
Author: User

This article is good, angular $q and promise!!.

--------------------------------------------------------------

A new deffered instance can be constructed by calling the $q. Defer ().
The Deffered object is used to associate an Promise instance with an API that marks the status of the task, either successfully or unsuccessfully.

Methods for Deffered objects
    • Resolve (value)--Incoming value resolves the derived promise. If value is a Deny object (rejection) that is constructed by $q. Reject, the promise will be rejected.
    • Reject (reason)--rejects the derived promise and provides the reason. This is equivalent to passing the $q. Reject constructed Deny object (rejection) as a parameter to resolve.
    • Notify (value)-Provides a status update during promise execution. This may be called several times before the promise is resolved or rejected.
Deffered properties of an object

promise–{promise}--the Promise object associated with the delay (deferred).

Commitment Interface | Promise API

When you create a deferred instance, a new Promise object is created, and you can get the reference by Deferred.promise.
The purpose of the Promise object is to allow the part of interest to get its execution results when the deferred task completes.

Methods for Promise Objects
    • Then (Successcallback, Errorcallback, Notifycallback)--whether the promise is handled or rejected, once the result is available, then the success/error callback function is called asynchronously as soon as the result is available. Pass a single argument when invoking a callback function: The reason for the result or rejection. Additionally, the notify callback may be called 0 to multiple times to provide a progress indication before the commitment is resolved or rejected.

This method returns a new promise object that is resolved or rejected according to Successcallback, Errorcallback's return value. It is also notified by the return value of the Notifycallback method. Promise cannot be resolved or rejected from the Notifycallback method.

    • catch (Errorcallback)--promise.then (NULL, errorcallback) shortcut
    • Finally (callback)--allows you to see whether a promise is being executed or rejected, but does not modify the last value value. This can be used to do work that frees up resources or cleans up useless objects, whether promise is rejected or resolved. For more information

Because finally is a reserved word keyword in the ES3 version of JavaScript and cannot be used as a property name, you need to call this method in the form of promise[' finally ' (callback) in order to fit the IE8.

Study the $q callback service, it seems that half-day is the appearance of indefinitely, feel the implementation of the asynchronous load function, or hands-on test and recorded, if not welcome correct (the background is ASP)

Callback for the first case, request for a single data source

Myapp.factory (' MyService ', function ($http, $q) {
return {
Getalldata:function () {
Define a callback service
var deferred = $q. Defer ();
$http. Get ('/api/values ')//Get a single data source at this time
. Success (function (result) {
Delegate the result to a callback function
Deferred.resolve (result);
})
. Error (function (result) {
Debugger
});
Returns the result of the callback function
return deferred.promise;
}
};
});
function Fetchctrl ($scope, $http, $templateCache, MyService, Myserviceall) {

$scope. Fetch = function () {

var result = Myservice.getalldata ();
Get data values with callback function results
Result.then (function (data) {
$scope. result = data;
};

}
}

Callback for the second case, a request to multiple data sources, and finally a collection of multiple results together with the return

Service statement
Myapp.factory (' Myserviceall ', function ($http, $q) {
return {
Getalldata:function () {
Define a callback service
var deferred = $q. Defer ();
To define two fetched source paths
var p1 = $http. Get ('/api/values ');
var P2 = $http. Get ('/api/values/0 ');
$q. All ([P1, p2])
. then (function (results) {
var aggregateddata = [];
Angular.foreach (results, function (result) {
Aggregateddata = Aggregateddata.concat (Result.data);
});
Delegate the result to a callback function
Deferred.resolve (Aggregateddata);
});
Returns the result of the callback function
return deferred.promise;
}
}
});

function Fetchctrl ($scope, $http, $templateCache, MyService, Myserviceall) {

$scope. Fetch = function () {
Get data values with callback function results
var result = Myserviceall.getalldata ();
Result.then (function (data) {

$scope. result = data;
})
};

}
Introduction to Methods

$q service Four method functions, divided into three classes according to personal understanding.

    1. Non-chained calls

      $q. When (value)

      Pass variable value, Promise.then () execute successful callback

      $q. All (Promises)

      Multiple promise must perform successfully to perform a successful callback, passing a value of an array or hash value, each of which is the Promise object corresponding to index.

    2. Error message Delivery

      $q. Reject (reason)

      Returns a failure reason, promise.then () execution failure callback

    3. Chained calls

      $q. Defer ()

      Returns a deferred object

    • Resolve (value) – Simplified description of the successful call function parameter for configuring the deferred object Promise
    • Reject (reason) – Simplified description The failed call function parameter for configuring the deferred object Promise
    • Promise-Simplified description of the Promise object after configuration
Personal Understanding Instructions

The default failure callback inside a chained call passes the exception backwards, so to avoid trouble and not care about the business logic error at every point, do not declare the exception handler at each and then () and declare it in the last then ().

      Promisex.then (function () {}). Then (function () {})
. Then (function (val) {},function (reason) {})

If you care about any possible business logic errors, return $q in the callback. Reject (); Pass error. No matter which callback function is executed, if there is no human return $q. Reject ();, if there is no execution error, the success signal is returned.

var deferred = $q. Defer ();
Deferred.resolve (1);
var promisea = deferred.promise;
Promisea
. Then (function (val) {$log. info (val); return ++val;})
. Then (function (val) {$log. info (val); return ++val;})
. Then (
Function (val) {$log. info (val); return ++val;},
Function (val) {$log. info (val)}
);

The console prints the two-to-one after the chain call is complete

var deferred = $q. Defer ();
Deferred.resolve (1);
var promisea = deferred.promise;
Promisea
. Then (function (val) {$log. info (val); return $q. Reject (15);})
. Then (function (val) {$log. info (val); return ++val;})
. Then (function (val) {$log. info (val); return ++val;})
. Then (function (val) {$log. info (val); return ++val;})
. Then (
Function (val) {$log. info (val); return ++val;},
Function (val) {$log. info (val)}
);

After the chain call completes, the console prints 1, 15, and you can see that the first return $q. Reject (15), the error callback function is not available until the last then (), so the exception is passed to the last, and the middle then () has no error callback function.

$q. When (' I love you! ')

Console print out I love you!;

$q. When ($q. Reject (' I Hate you! '))

The console prints out I Hate you!;

var Promisea = $q. When (' I love you! ');
var promiseb = $q. When (' Love story! ');
var promisec = $q. When ("Let ' t get wet!");
$q. All ([Promisea,promiseb,promisec]). Then (function (value) {
Value[0].then (function (value) {$log. info (value);})
Value[1].then (function (value) {$log. info (value);})
Value[2].then (function (value) {$log. info (value);})

Console print out I love You!,love story!, "let ' t get wet!

AngularJS $q and $q. All single data sources and multiple data sources merging (Promise's description)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.