Promises let the program run asynchronously and save time because it retrieves information from both URL at the same time.
Since the promises run asynchronously, for $q.all(promises) function, is it true that resultList[0] always has information from 1.json and resultList[1] has information from 2.json? The promises.push() might not have data from 1.json first right? Since the promise run asynchronously, it might only have the data from 2.json first before 1.json.
After running the page (using Promises) in other server, it gives error "Origin 'www.dns' not allowed by Access-Control-Allow-Origin." and "XMLHttpRequest cannot load 'a.json' due to access control checks", for Jquery GET method can use JSONP to solve the error. But is there a way that can solve in promises?
var promises = [];
var loadingJson = function(url){
var defer = $q.defer();
$http.get(url).then(function(results){
defer.resolve(results);
}, function(err){
defer.reject(err);
});
return defer.promise;
};
promises.push(loadingJson('example.com/1.json'));
promises.push(loadingJson('example.com/2.json'));
$q.all(promises).then(function(resultList){
// Your hanadling here, resultList contains the results of both API calls.
}, function(errList){
// Your error handling here.
});
Short answer: YES.
From the documentation of $q.all
(emphasis mine):
Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.
In short, the result of $q.all
will maintain the order of the original list, regardless of the order in which each promise individually resolves.