javascript - Make function work synchroniously (wait local events to get fired) -


i'm having problems javascript logic. when have function needs data event-handler generate result, possible data function? example, if call image() object or filereader() inside , wait load event fired in order generate proper return result.

simple example:

function imagesize(filename) {   funcresult = false;   var img = new image();   img.onload = function() {     myresult = {        width: img.width,       height: img.height       }     }   img.src = filename;   return funcresult; } 

course, doesn't work because load fires asynchronously after function has been executed. there workaround make function stop , listen main goal.

or bit more complex example (that can't work same reason).

function getimagesize(file) {   res = false;   if (window.filereader) {     var filereader = new filereader();     filereader.onload = function() {       var img = new image();       img.onload = function() {         res = {           width  : img.width,           height : img.height           };         }       img.src = this.result;       }     filereader.readasdataurl(file);   }   return res; } 

usage example:

var imagesize = getimagesize(myfileinput.files[0]); 

and handling result (perfect: wait)

if (!imagesize)   console.log('error'); else   console.log(imagesize.width + 'x' + imagesize.height); 

or (alternative: event handler)

imagesize.onload = function() {   console.log(this.width + 'x' + this.height);   } 

i'd make job linear (sync) , wait proper event handlers inside fire, not moving job outside of function scope (especially not global level).

my goal make one-function job, or worst case, define load event of function , listen result strict question "is somehow possible , if is, how?"

i understand how events work , know approach wrong that's illustration trying accomplish during last few days.

use callback inside function size:

function imagesize(filename, callback) {     funcresult = false;     var img = new image();     img.onload = function() {         var myresult = {              width: img.width,             height: img.height         }         callback(myresult)     }     img.src = filename; } 

and use it:

imagesize("test.jpg", function(sizeattributes) {     console.log(sizeattributes); }); 

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -