$q。所有承诺(访问控制允许来源)

$q. all Promises (Access-Control-Allow-Origin)

Promises 让程序 运行 异步并节省时间,因为它同时从两个 URL 检索信息。

由于异步承诺 运行,对于 $q.all(promises) 函数,resultList[0] 是否始终具有来自 1.json 的信息并且 resultList[1] 具有来自 2.json 的信息? promises.push() 可能没有来自 1.json 的数据,对吗?由于 promise 运行 是异步的,它可能只有 2.json 的数据先于 1.json.

在其他服务器运行ning页面(使用Promises)后,报错"Origin 'www.dns' not allowed by Access-Control-Allow-Origin."和"XMLHttpRequest cannot load 'a.json' due to access control checks",对于Jquery GET方法可以使用JSONP解决错误。但是有没有什么办法可以在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.
});

简短回答:


来自 documentation of $q.all(强调我的):

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.

简而言之,$q.all 的结果将保持原始列表的顺序,而不管每个 promise 单独解析的顺序如何。