Loop over javascript object whilst running async calls within -
i'm trying load multiple files using three.xhrloader , when completes want take key of object , add along file object (loadedfiles). problem have whenever try retrieve key object loaded returns last key in object array because callback load function gets called after loop has ended.
i've got this:
var loader = new three.xhrloader(); var loaded = 0; (var k in filestoload) { loader.load(filestoload[k], function(file) { console.log(k); // return last key when want //it return key loaded instead! loadedfiles[k] = file; loaded++; if (loaded == object.keys(filestoload).length) { console.log(loadedfiles); } }); }
you wrap three
calls in promise use promise.all
resolve once have. (pseudo code)
let promises = object.keys(filestoload) .map(k => { return new promise((res, rej) => { loader.load(filestoload[k], res, rej); //assuming loader has success, error callbacks }); }); promise.all(promises) .then(res => console.log(res)); // [file, file, file...]
obviously depending on browser support depends on es6 there es5 compatible promise libraries can use instead.
note files loaded in parallel when each promise created. requests pending before go promise.all
Comments
Post a Comment