Angular 来自数组的承诺链

Angular promise chain from array

我有一组 url urls = ["/url/file_1", "/url/file_2", "/url/file_3" ... "/url/file_n"] 和一个字符串变量 str = ""。 创建承诺链以使用 urls 中所有文件的内容填充 str 的最佳方法是什么?

这可以使用 $q.all。示例实现:

var urls = [ /* some urls */ ];
var promises = Array(urls.length);
var results = Array(urls.length);

for(var i = 0; i < urls.length; i++) {
    promises[i] = yourPromiseReturningFunction(urls[i]).then(function(result) {
        results[i] = result;
    });
}

$q.all(promises).then(function() {
    //Just an example, do whatever youw ant with your results here
    console.log(resulst.join('')); 
});

这可以用更优雅(更函数式)的方式来完成,这只是一个例子来说明它是如何实现的。在 $q.all here.

上查找文档

试试这样的东西:

var stringResult = '';
promises = [];
angular.forEach(urls, function (url) {
   promises.push($htpp({method: 'GET', url: url}))
}
$q.all(promises).then(
   function () {stringResult = stringResult.concat(res)})

你应该使用 $q.all

$q.all(urls.map(function(url){return $http.get(url)})) //create multiple requests and return the array of promises
    .then(function(results){ //an array of results
        results.forEach(function(res){ //response object https://docs.angularjs.org/api/ng/service/$http
            str += res.data; //concat strings assuming that all get calls will return string
        });
    });