When I was preloading images, my initial code looked like this:
function preLoad() {
var deferred = $q.defer();
var imageArray = [];
for (var i = 0; i < $scope.abbreviations.length; i++) {
imageArray[i] = new Image();
imageArray[i].src = $scope.abbreviations[i].imgPath;
}
imageArray.forEach.onload = function () {
deferred.resolve();
console.log('Resolved');
}
imageArray.forEach.onerror = function () {
deferred.reject();
console.log('Rejected')
}
return deferred.promise;
}
preLoad();
Initially, I thought the images were all loading correctly because I saw the 'Resolved' log.
However, someone later pointed out that only the first promise is resolved in the above code and it doesn't guarantee that all images are loaded before resolving the promise.
I was recommended to use $q.all
applied to an array of promises instead, leading to the following code:
function preLoad() {
var imageArray = [];
var promises;
for (var i = 0; i < $scope.abbreviations.length; i++) {
imageArray[i] = new Image();
imageArray[i].src = $scope.abbreviations[i].imgPath;
};
function resolvePromises(n) {
return $q.when(n);
}
promises = imageArray.map(resolvePromises);
$q.all(promises).then(function (results) {
console.log('array promises resolved with', results);
});
}
preLoad();
The updated code works, but I'm still trying to understand:
- what each function does;
- why using
$q.all
ensures that all images are loaded before resolving the promises.
The related documentation can be a bit difficult to comprehend.