I've been told that $http in Angular is asynchronous. However, for some purpose, I need to make sequential AJAX requests. I want to read all the files from a file list, and then get the number from all those files. For example:
content of "fileNames":
file1
file2
content of "file1":
1
content of "file2":
2
The following code will calculate the sum
<!DOCTYPE html>
<html>
<body>
<p id="id01"></p>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var fileString;
/* first AJAX call */
$.ajax({
url: 'fileNames', type: 'get', async: false,
success: function(content) {
fileString = content;
}
});
var fileList = fileString.split('\n');
var sum = 0;
for (var i = 0; i < fileList.length; i++) {
/* second AJAX call in getNumber function */
sum += getNumber(fileList[i]);
}
document.getElementById("id01").innerHTML = sum;
function getNumber(file) {
var num;
$.ajax({url: file, type: 'get', async: false,
success: function(content) {
num = content;
}
});
return parseInt(num);
}
</script>
</body>
</html>
Since the two $.ajax calls are sequential, I don't know how to achieve this functionality in AngularJS. Say, in the end, I want $scope.sum = 1 + 2.
Can someone make it work in AngularJS? Some simple code would be appreciated!
You could make use of promises and promise chaining (with
$q
and the promise returned by$http
). Example: In your controller you could do (after injecting$http
,$q
):Also see:
This does not mean that the calls are synchronous, but they are asynchronous and still does what you need in a more efficient way and easy to manage.
Demo