Detail Javacript and Promises in AngularJS

  • 2020-12-13 18:51:29
  • OfStack

For example, promise is used when the page calls api for google maps.


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 do I handle multiple asynchronous methods

What if there are many asynchronous methods that need to be executed sequentially? async1(success, failure), async2(success, failure), ... asyncN(success, failure), how do you deal with that?

The simplest might be something like this:


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

The above code is more difficult to maintain.

We can have all asynchronous methods execute with 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 result and status of the operation, and provides an instance of promise that can obtain the result of the operation. deferred can change the operation state.

promise provides an interface for interacting with the associated deferred.

When 1 deferred is created, it is equivalent to 1 pending state;
When the resolve method is executed, it corresponds to 1 resolved state.
When the reject method is executed, it is equivalent to 1 rejected state.

We can define the callback function after deferred has been created, and the callback function starts execution when prompted for the status of resolved and rejected. The asynchronous method does not need to know how the callback function operates; it only needs to tell the callback function to start executing when it gets the status of resolved or rejected.

■ 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 when the asynchronous method fails, the state becomes rejected.

→ Resolve or Reject This dererred

Suppose you have an asynchronous method like this: async(success, failure)


async(function(value){
  myFirstDeferred.resolve(value);
}, function(errorReason){
  myFirstDeferred.reject(errorReason);
})
 

In AngularJS, resolve and reject for $q are context-independent and can be written roughly as follows:

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){
  
  })
  
// Calling asynchronous methods 
async(anotherDeferred.resolve, anotherDeferred.reject);

anotherDeferred.promise
  .then(function(data){
  
  }, function(error){
  
  })
 

Above, both success methods are called if the asynchronous method async executes successfully.

→ Usually wraps asynchronous methods in 1 function


function getData(){
  var deferred = $q.defer();
  async(deferred.resolve,deferred.reject);
  return deferred.promise;
}

//deferred the promise The property was reached resolved, reject What the state needs to perform success and error methods 
var dataPromise = getData();
dataPromise
  .then(function(data){
    console.log('success');
  }, function(error){
    console.log('error');
  })
 

What if I only care about the success callback function?


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

How do You write the error callback function if you only care about it?


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

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

What if the callback returns the same result whether it succeeds or fails?


var finalCallback = function(){
  console.log(' This result is returned whether the callback succeeds or fails ');
}

dataPromise.then(finalCallback, finalCallback);

or

dataPromise.finally(finalCallback);
S value chain

Suppose you have an asynchronous method and use deferred.resolve to return 1 value.


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

0

Since we're returning promise, we can just keep going down then, then.


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

1

Above, the value of resolve becomes an argument for each chain.

S Promise chain


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

2

Of course, a more readable way is:


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

async1(10)
  .then(async2)
  .then(logValue);
 

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

From the point of view of catching exceptions, you can also write:


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

4

S $q. reject (reason)

Using this method, deferred can present error state and give a reason for error.


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

5

S $q. when (value)

Returns 1 promise with a value.


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

6

S $q. all (promisesArr)

Wait for all promise executions to complete.


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

7

Above is the detailed content of this article, I hope to help you learn, happy New Year!


Related articles: