The value is returned, but not from the detect function.
If you use a named function for a load event handler instead of an anonymous function, it more clearly shows what happens:
function handleLoad() { var result = [{ x: 45, y: 56 }]; return result; } function detect(URL) { var image = new Image(); image.src = URL; image.onload = handleLoad; }
The value is returned from the handleLoad function to the code that calls the event handler, but before that, the detect function has already exited. In detect is not even a return , so you cannot expect the result to be anything other than undefined .
One common way to handle asynchronous scripts like this is to use the callback function:
function detect(URL, callback) { var image = new Image(); image.src = URL; image.onload = function() { var result = [{ x: 45, y: 56 }]; callback(result); }; }
You call the detect function with a callback that is called after the value is available:
detect('image.png', function(result){ alert(result); });
Guffa
source share