When dealing with promise in angularjs, it sometimes comes across situations where you need to handle multiple promise.
The simplest treatment is that every promise is 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");
the 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 an array of promise, called as follows:
var all = $q. All ([One.promise, Two.promise, Three.promise]);
All.then (Success);
What is promise?
Promise is a method of handling values asynchronously, promise is an object that represents the final possible return value of a function or thrown exception, and when dealing with a remote object we can think of him as a proxy for a remote object. If promise is also a kind of asynchronous processing, then we will think of it and XHR and $.ajax what is the difference?
It is customary for JS to use closures or callbacks to correspond to data returned asynchronously, such as a XHR request after a page is loaded. We can interact with the data as if it had returned, without having to rely on the triggering of a callback function.
So what is Ng's promise to solve the problem? The callback has been in use for a long time, and it is usually difficult to debug when there is a callback that relies on other callbacks, and a processing error needs to be displayed after each step call. The difference is that promise provides another abstraction: These functions return promise objects.
Why use Promise
One of the rewards of using promise is the fixed thinking logic that escapes the callback. Promise makes the mechanism of asynchronous processing look more like synchronization, and based on the synchronization function we can capture the return value and the exception value as expected. You can catch errors at any point in your program and bypass subsequent code that relies on program exceptions, and we don't need to think about the benefits of this synchronization. Therefore, the purpose of using promise is to gain the ability to keep code running asynchronously while getting the combination of functionality and error-bubbling capabilities.
Promise is a first class object, with some conventions in his own.
• Only one resolve or reject will be called to.
• If promise are executed or rejected, the handlers that depend on them will still be invoked.
• Handlers are always invoked asynchronously.