The way multiple promise are handled in AngularJS

  • 2020-12-13 18:50:06
  • OfStack

When working with promise in AngularJS, you sometimes encounter situations where you need to work with more than one promise.

The easiest way to do this is to have each promise then. As follows:


var app = angular.module("app",[]);
app.controller("AppCtrl", function($q. $timeout){
var one = $q.defer();
var two = $q.defer();
var three = $q.defer();
$timeout(function(){
one.resolve("one done");
}, Math.random() * 1000)
$timeout(function(){
two.resolve("two done");
}, Math.random() * 1000) 
$timeout(function(){
three.resolve("three done");
}, Math.random() * 1000) 
functioin success(data){
console.log(data);
}
one.promise.then(success);
two.promise.then(success);
three.promise.then(success);
})

Is there a better way?

The $q. all method can accept 1 array of promise, called as follows:


var all = $q.all([one.promise, two.promise, three.promise]);
all.then(success);

What is a promise & # 63;

promise is a method of handling values asynchronously. promise is an object that represents the final possible return value of a function or the exception that is thrown. When dealing with a remote object, we can think of it as a proxy for the remote object. If promise is another example of asynchronous processing, how does it differ from XHR and $.ajax?

It is customary for js to use closures or callbacks to correspond to data returned asynchronously, such as XHR requests after the page has loaded. We can interact with the data normally as if it had already returned one without relying on the trigger of the callback function.

So what problem does promise propose to solve? Callbacks have been used for a long time, and it is often very difficult to debug if there are callbacks that depend on other callbacks, requiring processing errors to be displayed after each step. In contrast, promise provides another abstraction: these functions return promise objects.

Why use promise

One of the gains of using promise is to escape the fixed thinking logic of the callback. promise makes the mechanism of asynchronous processing look more like synchronization, based on the synchronization function we can catch return values and outliers as expected. You can catch errors at any point in your program and bypass subsequent code that depends on your program exceptions without thinking about the benefits of this synchronization. So the purpose of using promise is to capture the ability to combine functionality and bubble errors while maintaining the ability for code to run asynchronously.

promise is a first-class object and comes with 1 set of conventions.

The & # 8226; Only 1 resolve or reject will be called.

The & # 8226; If promise is executed or rejected, the handlers that depend on them will still be called.

The & # 8226; Handlers are always called asynchronously.


Related articles: