My goal is to use the THREE.XHRLoader to load multiple files, then add the key of each loaded object along with the file to another object called loadedFiles. The issue I'm facing is that when trying to retrieve the key for each loaded object, it always returns the last key in the object array because the callback function gets executed after the loop has finished.
This is what my code looks like:
var loader = new THREE.XHRLoader();
var loaded = 0;
for (var k in filesToLoad) {
loader.load(filesToLoad[k], function(file) {
console.log(k); // Instead of getting the correct key for the loaded file,
//it always returns the last key.
loadedFiles[k] = file;
loaded++;
if (loaded == Object.keys(filesToLoad).length) {
console.log(loadedFiles);
}
});
}