I have a JS function where a value is computed and this value should be returned but I get everytime undefined
but if I console.log()
the result within this function it works. Could you help?
function detect(URL) {
var image = new Image();
image.src = URL;
image.onload = function() {
var result = [{ x: 45, y: 56 }]; // An example result
return result; // Doesn't work
}
}
alert(detect('image.png'));
The value is returned, but not from the
detect
function.If you use a named function for the load event handler instead of an anonymous function, it's clearer what's happening:
The value is returned from the
handleLoad
function to the code that calls the event handler, but thedetect
function has already exited before that. There isn't even anyreturn
statement in thedetect
function at all, so you can't expect the result to be anything butundefined
.One common way of handling asynchronous scenarios like this, is to use a callback function:
You call the
detect
function with a callback, which will be called once the value is available:I get it myself:
I didn't know that I can assign a variable to that (for me looking already assigned) onload.
detect()
doesn't return any value. If you want to get an alert, replacereturn result;
byalert(result)
.An analysis of your code:
Your function
detect
doesn't return anything, which is why thealert
is showing "undefined". Thereturn
statement that you claim doesn't work is returning from the anonymous function you assign toimage.onload
, and probably works fine if you would call that function.This is because the function detect doesn't return anything since the load event happens after the function is finished. And you forgot to append the image to something so it never loads.
You could do something like:
fiddle here http://jsfiddle.net/LVRuQ/