I need to be able to loop through an object of images and perform an asynchronous function on each image one at a time.
I have it kind of working if I convert the images object to an array but I want to do this with a for...in loop so I can use the image keys as well. I also need to be able to perform an action at the end as I am currently.
var images = {
ABD: '1464685684713583388647.jpg',
ABY: '1457524543088191607099.jpg',
ADV: '1478877365443818880647.jpg',
AFD: '1457527861824290195088.jpg',
}
var imagesArray = Object.values(images);
var len = imagesArray.length;
function asynchronousImageFunction (key, image, onSuccess, onFail) {
setTimeout(function () {
console.log(key);
console.log(image);
onSuccess();
}, Math.random() * 1000)
}
(function loop(i) {
if (i < len) {
new Promise(function (resolve, reject) {
asynchronousImageFunction ('key', imagesArray[i], resolve, reject);
}).then(loop.bind(null, i+1));
} else {
console.log('end');
}
})(0);
The order isn't important but having them call one after the other is, and having an onComplete or end call is also needed. I just can't get my head round it, can anyone help?