I’m faced with a challenging scenario that’s got me puzzled:
-I’ve got an array of 10 objects, each with two properties: IDNum
and imageURL
.
-Only 3 of these objects actually have their imageURL
property set (at index
positions [0, 4, 9]
), and now I need to retrieve their images.
-I swiftly create another array named imageURLsArray
containing these 3 URLs, and then use .map
to attach a Promise
to each one:
// (there’s some THREE.js code but focus on the issue of enumerating Promises in Javascript)
function getTextures(theImageURLsArray) {
const loader = new THREE.TextureLoader(); // This lets you load images from remote URLs using THREE.js
return theImageURLsArray.map((currentURL, index) => {
console.log(" Inside '.map', currentURL # ", index, " is: ", currentURL);
return new Promise(function(resolve, reject) {
console.log(" >>Inside 'new Promise' — will now call loader.load() function!");
loader.load(currentURL, function(theReturnedLoadedTexture) {
console.log("\n RETURNED from 'loader.load()', index#", index, ", with currentURL = ", currentURL);
console.log(" Will now call 'resolve()' with this Texture!");
resolve(theReturnedLoadedTexture)
},
function(err) {
reject(err);
})
})
})
}
To make it all come together, follow these steps:
Promise.all(getTextures(imageURLsArray))
.then(returnedTexturesArray => {
console.log("Here are the returned textures:");
console.log(returnedTexturesArray);
theTexturesArray = returnedTexturesArray;
// Manually iterate through these textures to check them out:
for(z = 0; z < theTexturesArray.length; z++) {
tempTexture = theTexturesArray[z];
console.log("tempTexture # ", z, "'s IMAGE property = ", tempTexture.image.currentSrc);
}
// Use these Textures to map onto 3D Materials...
})
.catch(err => console.error(err))
Everything works flawlessly except for one thing - the order in which the Promises
return is not guaranteed. This means they may come back in a different order than they were created in.
This causes a mismatch between the original imageURLsArray
and the resulting returnedTexturesArray
.
We need to ensure that Image # 4 doesn’t mistakenly end up in Cell # 0 when loading images into something like a grid-Table.
The challenge is maintaining the correct ordering of images even when working with a large scale of up to 1000 objects and corresponding images in an efficient manner.