javascript - How to load images with chained Promises -


i'm having trouble loading images script of chained promises - turn undefined end. have 404 error don't quite understand i've confirmed sources valid, admit i'm still noob debugging in async context. here fiddle in question. i've been chewing on 1 couple days , use nudge or 2 me headed in right direction. think may problem area:

function loadimagepromises() {     var imageloadpromises = [];     ( var  = 0; < sources.length; i++ ) {         imageloadpromises.push(              imgload( sources[i] ).then(function(response) {                 var myimage = new image();                 myimage.src = response; // response blob             }, function(error) {                 console.log("there error when image loaded after download: " + error);             }) );     }     console.log( imageloadpromises );     return imageloadpromises; } 

as context, i'm writing image loader script using promises three.js program have. no need load images dom - i'll use them later textures in webgl visualization.

note: here's earlier , simpler fiddle working end-to-end , outputting dom.

probably other considerations here success handler isn't returning explicitly, it's implicitly returning undefined:

function(response) {   var myimage = new image();   myimage.src = response;   // if want promise resolve useful value put   // below, whatever want e.g:   return myimage; } 

re: errors: should not shadow error in error handler, use lowercase error. also, when using console.log/console.error can use , chain parts of message presents richer message string used when concatenating.

e.g.

console.error("there error when image loaded after download: ", error); 

fwiw reduce of tedious iteration/collection here using map map each source promise:

function loadimagepromises() {   return sources.map(function(source) {     return imgload(source).then(function(response) {     // ...     }); } 

edit re: waiting image objects have loaded

return imgload(source).then(function(response) {   var imageurl = window.url.createobjecturl(response);   var myimage = new image();    return new promise(function(resolve, reject) {     myimage.onload = function () {       // image has loaded       resolve(myimage);     }      // todo error handling      myimage.src = imageurl;   }); }, console.error); }); 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -