Reputation: 6978
This snippet is part of a bigger directive:
var imageArray = [];
for (var i = 0; i < $scope.abbreviations.length; i++) {
imageArray[i] = new Image();
imageArray[i].src = $scope.abbreviations[i].imgPath;
};
console.log(imageArray);
function preLoad() {
var promises = [];
function loadImage(src) {
return $q(function (resolve, reject) {
var image = new Image();
image.src = src;
image.onload = function () {
resolve(image);
console.log('onload:', src);
};
image.onerror = function (e) {
reject(e);
console.log('onerror:', e);
};
})
}
imageArray.forEach(function (src) {
console.log('forEach:', src);
promises.push(loadImage(src));
});
return $q.all(promises).then(function (results) {
console.log('Promises resolved with', results);
$scope.results = results;
});
}
preLoad().then(function () {
console.log('Ready for next activity...');
});
and this screenshot shows the logs in my console:
Question: why the loading function fails and, as a consequence, the promises don't get resolved?
Upvotes: 0
Views: 67
Reputation: 106395
The problem is here:
imageArray.forEach(function(src) {
...
}
You pass into a forEach
callback an element of imageArray
- but that's already an Image object. That's why when you assign it into a new Image's src, loading fails.
The easiest solution would be skipping that loop in the beginning of your code, and augment forEach
callback so that it works with the original object. In fact, it's cleaner to use .map
with returning the result:
promises = $scope.abbreviations.map(function(imgObj) {
return loadImage(imgObj.imgPath);
});
Upvotes: 1