I have an array of urls urls = ["/url/file_1", "/url/file_2", "/url/file_3" ... "/url/file_n"]
and a string variable str = "".
What is a best way to create a promise chain to fill str with content of all files from the urls?
3 Answers
You should use $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
});
});
1 Comment
LionC
Very elegant solution! Maybe add some text do explain what you are doing and how it works
That is possible using $q.all. Example implementation:
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(''));
});
This can be done in more elegant(more functional-style) ways, this is just an example to show how it is possible. Find the documentation on $q.all here.
Comments
Try something like:
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 Comment
LionC
Keep in mind that this will append the results in random order and does not allow to react to all promises being resolved