Detailed promises_javascript skills in Javacript and Angularjs

Source: Internet
Author: User

For example, when the page calls the Google Maps API, it uses the promise.

function success (position) {
  var cords = position.coords;
  Console.log (Coords.latitude + coords.longitude);
}

Function error (ERR) {
  Console.warn (err.code+err.message)
}

navigator.geolocation.getCurrentPosition ( Success, error);
 

How to handle multiple asynchronous methods

What if there are many asynchronous methods that need to be executed in sequence? 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 (null, NULL);
    ..
  }, NULL)
}, NULL
 

The above code is more difficult to maintain.

We can have all asynchronous methods executed after the completion of a notification.

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 results and status of the operation, and provides a promise instance that can be used to obtain the result of the operation. Deferred can change the operating state.

Promise provides an interface to interact with the associated deferred.

When creating a deferred, the equivalent of 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 we create the deferred, and the callback function starts executing after the resolved and rejected status prompts. Asynchronous methods do not need to know how the callback function operates, only to notify the callback function to begin execution after getting the resolved or rejected state.

Basic usage

→ Create Deferred

var myfirstdeferred = $q. Defer ();

Here, for myfirstdeferred this deferred, the state is pending, and then, when the asynchronous method executes successfully, the state becomes resolved, and the state becomes rejected when the asynchronous method fails to execute.

→resolve or reject this dererred

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

Async (function (value) {
  myfirstdeferred.resolve (value);
}, Function (Errorreason) {
  Myfirstdeferred.reject (Errorreason);
})
 

In Angularjs, the resolve and reject of the $q are not dependent on the context and can be written roughly like this:

Async (Myfirstdeferred.resolve, myfirstdeferred.reject);

→ Use of 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 asynchronous Method
Async ( Anotherdeferred.resolve, anotherdeferred.reject);

Anotherdeferred.promise
  . Then (function (data) {}
  
  , function (Error) {
  
  })
 

Above, if the asynchronous method async successfully executed, two success methods will be invoked.

→ Usually wrap the asynchronous method into a function

function GetData () {
  var deferred = $q. Defer ();
  Async (deferred.resolve,deferred.reject);
  return deferred.promise;
}

Deferred's Promise attribute records the success and error methods required to achieve resolved, reject status,
var datapromise = GetData ();
Datapromise
  . 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 you only focus on the error callback function?

Datapromise
  . Then (null, function (Error) {
    console.log (' error ');
  })
  
or

Datapromise.catch (function (Error) {
  console.log (' error ');
})
 

What if the callback succeeds or fails to return the same result?

var finalcallback = function () {
  Console.log ("returns this result regardless of callback success or failure");
}

Datapromise.then (Finalcallback, finalcallback);

Or

Datapromise.finally (Finalcallback);
Value chain type

Suppose you have an asynchronous 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 to then, then go on.

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 resolve out becomes the actual parameter of each chain.

Promise Chain Type

function Async1 (value) {
  var deferred = $q. Defer ();
  var result = value * 2;
  Deferred.resolve (result);
  return deferred.promise;
}

function Async2 (value) {
  var deferred = $q. Defer ();
  var result = value + 1;
  Deferred.resolve (result);
  return deferred.promise;
}

var promise = Async1
  . Then (function (x) {return
    async2 (x);
  })
  
Promise.then (function (x) {
  console.log (x);
}) 
 

Of course a more readable form is:

function Logvalue (value) {
  console.log (value);
}

ASYNC1 (then). (
  async2)
  . Then (Logvalue);
 

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

From the angle of the catch exception, you can also write this:

ASYNC1 ()
  . Then (ASYNC2)
  . Then (async3).
  catch (Handlereject)
  . Finally (freeresources);
 

$q. Reject (reason)

Using this method, the deferred can render an error state and give a reason for the 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 with a 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],
    value2 = values[1],
    ...
    Valuen = Values[n];
    
  Console.log (' all done ');
}

The above is the detailed content of this article, I hope to learn some help, Happy New Year!

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.