Is it possible to wrap an asynchronous event and its callback in a function that returns a boolean?

Posted by Rob Flaherty on Stack Overflow See other posts from Stack Overflow or by Rob Flaherty
Published on 2010-12-28T20:48:31Z Indexed on 2010/12/28 20:54 UTC
Read the original article Hit count: 153

Filed under:
|
|

I'm trying to write a simple test that creates an image element, checks the image attributes, and then returns true/false. The problem is that using the onload event makes the test asynchronous. On it own this isn't a problem (using a callback as I've done in the code below is easy), but what I can't figure out is how to encapsulate this into a single function that returns a boolean.

I've tried various combinations of closures, recursion, and self-executing functions but have had no luck.

So my question: am I being dense and overlooking something simple, or is this in fact not possible, because, no matter what, I'm still trying to wrap an asynchronous function in synchronous expectations?

Here's the code:

var supportsImage = function(callback) {
  var img = new Image();
  img.onload = function() {
    //Check attributes and pass true or false to callback
    callback(true);
  };
  img.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
};

supportsImage(function(status){
  console.log(status);  
});

To be clear, what I want is to be able to wrap this in something such that it can be used like:

if (supportsImage) {
  //Do some crazy stuff
}

Thanks!

(Btw, I know there are a ton of SO questions regarding confusion about synchronous vs. asynchronous. Apologies if this can be reduced to something previously answered.)

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about asynchronous