Detailed explanation of Promises_javascript skills in Javacript and AngularJS

Source: Internet
Author: User
This article mainly introduces detailed information about Promises in javacrept and AngularJS. promise is a good solution for Javascript asynchronous programming ., For more information, see 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 many asynchronous methods need to be executed in order? Async1 (success, failure), async2 (success, failure),... asyncN (success, failure), what should we do?

The simplest one may be:

async1(function(){  async2(function(){    ...    asyncN(null, null);    ...  }, null)}, null) 

The above code is difficult to maintain.

We can send a notification after all asynchronous methods are executed.

var counter = N;function success(){  counter--;  if(counter === 0){    alert('done');  }}async1(success);async2(success);...asyncN(success); 

■ What is Promise and Deferred?

Deferred indicates the result of an asynchronous operation, provides an interface for displaying the operation result and status, and provides a promise instance related to the operation result. Deferred can change the operation status.

Promise provides an interface for interacting with related deferred.

When a deferred is created, 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.

After the deferred is created, we can define the callback function. The callback function starts to run after receiving the resolved and rejected status prompts. The asynchronous method does not need to know how the callback function operates. It only needs to notify the callback function to start execution after the resolved or rejected status is obtained.

■ Basic usage

→ Create deferred

Var myFirstDeferred = $ q. defer ();

Here, for the deferred myFirstDeferred, the state is pending. Next, when the Asynchronous Method is successfully executed, the state changes to resolved. When the asynchronous method fails to be executed, the state changes to rejected.

→ 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, $ q's resolve and reject do not depend on context, and can be written like this:

Async (myFirstDeferred. resolve, myFirstDeferred. reject );

→ Use 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 the Asynchronous Method async (anotherDeferred. resolve, anotherDeferred. reject); anotherDeferred. promise. then (function (data) {}, function (error ){})

If the Asynchronous Method async is successfully executed, both success methods will be called.

→ The Asynchronous Method is usually wrapped into a function.

Function getData () {var deferred = $ q. defer (); async (deferred. resolve, deferred. reject); return deferred. promise;} // The promise attribute of deferred records the success and error method var dataPromise = getData () to be executed to reach the resolved state. then (function (data) {console. log ('success');}, function (error) {console. log ('error ');})

How do I write the success callback function?

dataPromise  .then(function(data){    console.log('success');  }) 

How do I write the error callback function?

DataPromise. then (null, function (error) {console. log ('error');}) or dataPromise. catch (function (error) {console. log ('error ');})

What if the same result is returned regardless of whether the callback is successful or fails?

Var finalCallback = function () {console. log ('Return this result no matter whether the callback is successful or failed ');}

DataPromise. then (finalCallback, finalCallback );

Or

DataPromise. finally (finalCallback );
■ Value Chain

Suppose there is an asynchronous method, and a value is returned using deferred. resolve.

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

Since promise is returned, we can continue then and then.

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 produced by resolve becomes the real parameter of each chain.

■ Promise chain

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(10)  .then(function(x){    return async2(x);  })  promise.then(function(x){  console.log(x);})  

Of course, a easier way to read is:

function logValue(value){  console.log(value);}async1(10)  .then(async2)  .then(logValue); 

The Return Value of the async1 method is a real parameter in the success method of the then method.

If you want to capture exceptions, you can write as follows:

async1()  .then(async2)  .then(async3)  .catch(handleReject)  .finally(freeResources); 

■ $ Q. reject (reason)

This method enables deferred to display the error status and provides 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 until all promise execution is 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 it will help you learn and enjoy the 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.