[AngularJS] ANGULARJS Series (7) The promise of advanced article

Source: Internet
Author: User

Directory

    • Using Promise
    • Then chain
    • Extended

In the previous section, we used then in HTTP and returned a ' lingering object ' in Ngresource.

This section describes the promise in angular.

I think the promise in JS can be likened to the await of a task in C # to implement callbacks when synchronizing.

Using Promise

Html

    <input type= "checkbox" ng-model= "flag"/>    <button ng-click= "func ()" >Test</button>

Controller

[' $scope ', ' $q ', function (scope, q) {            scope.func = function () {                var defer = Q.defer ();//create 1 lazy load objects or new 1 units of work 
   var promise = Defer.promise;//defer The core of the object contains a handle to the callback function                Promise.then (function (data) {                    var msg = ' success: ' + data;                    Console.log (msg);                }, function (data) {                    var msg = ' failed: ' + data;                    Console.log (msg);                }, function (data) {                    var msg = ' Notification: ' + data;                    Console.log (msg);                });                Defer.notify (' Start execution ');                Scope.flag? Defer.resolve (' checked '): Defer.reject (' unchecked ');            }
}]

Click the button:

Here we can see how $q the defer() method created by the object has

    • resolve(value): Used to execute deferred promise , value can be a string, object, etc.
    • reject(value): Used to reject deferred promise , value can be a string, object, etc.
    • notify(value): Gets deferred promise the execution state, and then uses this function to pass it.
    • then(successFunc, errorFunc, notifyFunc): Whether it promise succeeds or fails, when the result is available, it is then immediately called asynchronously successFunc , or ' Errorfunc ', and promise may be called 0 to several times before being executed or rejected notifyFunc to provide a hint of the process state.
    • catch(errorFunc)
    • finally(callback)

Then chain

We changed the code slightly (this code is incomplete and only defines the success method).

            SCOPE.FUNC2 = function () {                var defer = Q.defer ();                var promise = Defer.promise;                Promise.then (function (data) {                    var msg = ' success: ' + data;                    return msg;                }). Then (function (data) {                    console.log (data);                });                Defer.notify (' Start execution ');                Scope.flag? Defer.resolve (' checked '): Defer.reject (' unchecked ');            }

Here to illustrate the then function and the Reject function. Let's see the demo.

                Promise.then (function (data) {                    var msg = ' success: ' + data;                    return msg;                }, function (data) {                    var msg = ' failed: ' + data;                    return msg;                }). Then (function (data) {                    console.log (data);                }, Function (Erro) {                    console.log (' Erro: ' + Erro);                });

The Erro prefix is added to the Erro function in the second then.

We find that this method is not called.

After modifying the promise:

                Promise.then (function (data) {                    var msg = ' success: ' + data;                    return msg;                }). Then (function (data) {                    console.log (data);                }, Function (Erro) {                    console.log (' Erro: ' + Erro);                });

You can also return to promise

                Promise.then (function () {                    var thendefer = Q.defer ();                    $timeout (function () {                        if (scope.flag)                            thendefer.resolve (' done success ');                        Thendefer.reject (' Done faild ');                    };                    return thendefer.promise;                }). Then (function (data) {                    console.log (data);                }, Function (Erro) {                    console.log (' Erro: ' + Erro);                });

    • The Promise chain will pass the previous then return result to the next then (if not undefined) of the call chain.
    • If you then return a Promise object, the next one then will only be called when the promise is processed.
    • catchprovides an exception-handling point for the entire chain at the end of the chain
    • The end of the chain finally will always be executed, regardless of whether the promise is processed or rejected, and the cleanup function

Extended

$q.all(), allowing you to wait for parallel promise processing, when all promise are processed, call a common callback

$q.when(), if you want to create a promise with a common variable

This address: http://www.cnblogs.com/neverc/p/5928285.html

[AngularJS] ANGULARJS Series (7) The promise of advanced article

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.