Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

javascript - image.onload function with return

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'));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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 the detect function has already exited before that. There isn't even any return statement in the detect function at all, so you can't expect the result to be anything but undefined.

One common way of handling asynchronous scenarios like this, is to use a 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, which will be called once the value is available:

detect('image.png', function(result){
  alert(result);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...