My objective is to run a for loop 10 times in order to download a 3MB file from my server and record the time it takes (in ms). By repeating this process 10 times, I can then calculate the average download speed for the client.
However, I am facing an issue with the following loop:
$scope.startTest = function () {
var dlTime = 0;
for (var i = 0; i < 10; i++) {
var wait = getLargeData();
wait.then(function(result) {
dlTime += result.dlTime;
$scope.message += "\n finished loop " + i;
});
}
$scope.message += "\n Total download time: " + dlTime;
}
The output of the above code snippet displays:
finished loop 10
finished loop 10
finished loop 10
finished loop 10
finished loop 10
finished loop 10
finished loop 10
finished loop 10
finished loop 10
finished loop 10
Total download time: 0
I understand that the issue lies in the asynchronous nature of the calls. How can I ensure that the loop waits for the .then call to complete before proceeding?
Edit: It is important to note that getLargeData() does return a promise
function getLargeData() {
var loadTime = 0;
var dlSpeed = 0;
var promise = $q.defer();
var startTime = new Date();
$networkSvc.getLargeData()
.success(function (data) {
loadTime = new Date() - startTime;
dlSpeed = 3 / (loadTime / 1000);
var ret = { loadTime: loadTime, dlSpeed: dlSpeed };
promise.resolve(ret);
return promise.promise;
})
.error(function() {
$scope.message = "Error - could not contact server.";
});
return promise.promise;
}