0

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 3

4

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
        });
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Very elegant solution! Maybe add some text do explain what you are doing and how it works
1

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

1

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

Keep in mind that this will append the results in random order and does not allow to react to all promises being resolved

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.