The promises in Javacript and Angularjs

Source: Internet
Author: User

Promise is a good solution for JavaScript asynchronous programming. For an async method, execute a callback function.

For example, the page calls the Google Maps API when the use of promise.

function Success (position) {    var cords = position.coords;     + coords.longitude);} function error (ERR) {    Console.warn (err.code+err.message)}navigator.geolocation.getcurrentposition ( Success, error);

How to handle multiple async methods

What if there are many asynchronous methods that need to be executed sequentially? ASYNC1 (success, Failure), ASYNC2 (success, Failure), ... asyncn (success, failure), how to deal with it?

The simplest of these may be written as follows:

Async1 (function() {    async2(function() {        ...        ASYNCN (nullnull);        ...     NULL  null)

The above code is more difficult to maintain.

We can get a notification after all the async methods have been executed.

var counter = N; function success () {    counter--;     if (counter = = 0) {        alert (' done ');    }} ASYNC1 (success); Async2 (success); ASYNCN (success);

What are promise and deferred?

Deferred represents the result of an asynchronous operation, provides an interface to display the result and status of the operation, and provides a promise instance that can get the result of the operation. Deferred can change the state of operation.

Promise provides an interface for interacting with related deferred.

When creating a deferred, it is equivalent to a pending state;
When the Resolve method is executed, it is equivalent to a resolved state.
When the Reject method is executed, it is equivalent to a rejected state.

We can define the callback function after the deferred is created, and the callback function starts execution after getting the status hint of resolved and rejected. The Async method does not need to know how the callback function operates, but only notifies the callback function to start executing after getting the resolved or rejected state.

Basic usage

→ Create Deferred

var myfirstdeferred = $q. Defer ();

Here, for myfirstdeferred this deferred, the state is pending, next, when the Async method executes successfully, the state becomes resolved, and when the Async method execution fails, the state becomes rejected.

→resolve or reject this dererred

Suppose there is an async method: Async (success, failure)

Async (function(value) {    function(errorreason) {    Myfirstdeferred.reject ( Errorreason);})

In Angularjs, the $q resolve and reject are not context-sensitive and can be roughly written like this:

Async (Myfirstdeferred.resolve, myfirstdeferred.reject);

→ Use the promise in deferred

var myfirstpromise = myfirstdeferred.promise;myfirstpromise    . Then (function( Data) {        function(Error) {        })

Deferred can have multiple promise.

var anotherdeferred = $q. defer (); Anotherdeferred.promise    . Then (function(data) {        },function(Error) {        })    // Call async method Async ( Anotherdeferred.resolve, Anotherdeferred.reject); Anotherdeferred.promise    . Then (function (data) {        function(Error) {        })

Above, if the Async method async executes successfully, two success methods will be called.

→ usually wrap an async method into a function

function GetData () {    var deferred = $q. defer ();    Async (Deferred.resolve,deferred.reject);     return deferred.promise;} // The Promise property of deferred records the success and error methods required to achieve resolved, reject State var datapromise = getData ();d atapromise    . Then (function(data) {        Console.log (' success ');     function (Error) {        console.log (' error ');    })    

What if you only focus on the success callback function?

datapromise    . Then (function(data) {        Console.log (' success ');    })

What if I just focus on the error callback function?

datapromise    . Then (nullfunction(error) {        console.log (' error ') );    })    or datapromise. Catch (function(error) {    console.log (' error ');})

If the callback succeeds or fails, the same result is returned?

var function () {    console.log (' return this result regardless of callback success or failure ');} Datapromise.then (Finalcallback, finalcallback); or datapromise. finally (Finalcallback);

Value-Chain

Suppose you have an async method that returns a value using Deferred.resolve.

function Async (value) {    var deferred = $q. defer ();     var result = Value/2;    Deferred.resolve (result);     return deferred.promise;}

Since the return is promise, we can continue then and then go down.

var promise = Async (8)    . Then (function(x) {        return x+1;    })    . Then (function(x) {        return x*2;    })    Promise.then (function(x) {    console.log (x);})  

Above, the value of resolve becomes the argument of each chain type.

Promise Chain Type

functionasync1 (value) {varDeferred =$q. Defer (); varresult = value * 2;    Deferred.resolve (result); returndeferred.promise;}functionAsync2 (value) {varDeferred =$q. Defer (); varresult = value + 1;    Deferred.resolve (result); returndeferred.promise;}varPromise = Async1 (10). Then (function(x) {returnASYNC2 (x); }) Promise.then (function(x) {console.log (x);}) 

Of course, an easier-to-read notation is:

function Logvalue (value) {    console.log (value);} Async1(    async2) then    (logvalue);

The return value of the Async1 method becomes an argument in the success method in the then method.

If you are capturing an exception from the angle, you can also write:

async1 (). Then (    async2). Then    (async3)    . Catch (Handlereject)    . finally (freeresources);

$q. Reject (reason)

Using this method allows deferred to render an error state, and gives a reason for error.

var promise = Async (). Then (function(value) {    if(true) {         return  value;     Else {        return $q. Reject (' value is not satisfied ');    }})

$q. When (value)

Returns a promise and takes the value.

function getdatafrombackend (query) {    var data = searchincache (query);     if (data) {        return  $q. When (data);     Else {        reutrn makeaasyncbackendcall (query);}    }

$q. All (Promisesarr)

Wait for all promise execution to complete.

var allpromise = $q. All ([    async1 (),    async2 (),    ...    ASYNCN ();]) Allproise.then (function(values) {    var value1 = values[0],        = Values[1],        ...         = Values[n];            Console.log (' all done ');})

The promises in Javacript and Angularjs

Related 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.