使功能同步工作(等待本地事件被触发)

Wh1*_*Ck5 1 javascript synchronous javascript-events

我遇到了JavaScript逻辑问题.当我们有一个需要来自事件处理程序的数据来生成结果的函数时,是否可以将该数据恢复功能?例如,如果我们调用Image()object或FileReader()inside并等待其load事件被触发以生成正确的返回结果.

简单的例子:

function imageSize(filename) {
  funcResult = false;
  var img = new Image();
  img.onload = function() {
    myResult = { 
      width: img.width,
      height: img.height
      }
    }
  img.src = filename;
  return funcResult;
}
Run Code Online (Sandbox Code Playgroud)

当然,它不起作用,因为load在函数执行后异步发生火灾.但是有一些解决方法可以使功能停止和收听,这是我的主要目标.

或者更复杂的例子(也出于同样的原因也无法工作).

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;
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

var imageSize = getImageSize(myFileInput.files[0]);
Run Code Online (Sandbox Code Playgroud)

和处理结果为(完美:等待)

if (!imageSize)
  console.log('error');
else
  console.log(imageSize.width + 'x' + imageSize.height);
Run Code Online (Sandbox Code Playgroud)

或(替代方案:来自事件处理程序)

imageSize.onload = function() {
  console.log(this.width + 'x' + this.height);
  }
Run Code Online (Sandbox Code Playgroud)

我想让这个工作成为线性(同步)并等待内部正确的事件处理程序触发,而不是在函数范围之外移动作业(特别是不到全局级别).

我的目标是使这个单功能工作,或者最坏的情况,定义load该功能的一些事件并听取结果,所以我的严格问题是"这是否可行,如果是,如何?"

我理解事件是如何运作的,并且知道这种方法是错误的,但这仅仅是我在过去几天里想要完成的一个例子.

tym*_*eJV 5

在函数内部使用回调来获取大小:

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;
}
Run Code Online (Sandbox Code Playgroud)

并使用它:

imageSize("test.jpg", function(sizeAttributes) {
    console.log(sizeAttributes);
});
Run Code Online (Sandbox Code Playgroud)