2015-10-08 70 views
0

我有一個網址陣列urls = ["/url/file_1", "/url/file_2", "/url/file_3" ... "/url/file_n"] 和一個字符串變量str = ""。 什麼是創建承諾鏈以填充str以及來自urls的所有文件的內容的最佳方式?來自陣列的角度承諾鏈

回答

4

您應該使用$ 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 
     }); 
    }); 
+0

非常優雅的解決方案!也許添加一些文字可以解釋你在做什麼以及它是如何工作的 – LionC

1

這是可能的使用$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.allhere的文檔。

1

試着這麼做:

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

請記住,這將追加隨機順序結果並不允許對所有的承諾是反應解決 – LionC

+0

公平點,謝謝。包含在編輯 –