【问题标题】:how to return value from this async function? img.onLoad event如何从此异步函数返回值? img.onLoad 事件
【发布时间】:2022-09-22 23:37:47
【问题描述】:

如何从函数getImgSize(imgSrc) 返回height?请记住,onload() 是异步的。

function getImgSize(imgSrc) {
  const img = new Image();

  img.onload = function() {
    const height = img.height;
  }
  img.src = url;
}
  • 您不能从事件处理程序返回任何内容。您试图在这里解决的实际问题是什么?
  • 我拿了 20 张照片。我想将它们从最小的一个到最大的一个。排序后,我想显示它。

标签: javascript asynchronous return onload onload-event


【解决方案1】:

您可以将其包装在 promise(称为 "promisification")中:

function getImgSize(imgSrc){
  const img = new Image();

  img.src = imgSrc;

  return new Promise((resolve, reject) => {
    img.onload = function() {
      const height = img.height; 

      resolve(height); // Promise resolves to this value
    };

    img.onerror = function(error) {
      reject(error); // Promise rejects with the error
    };
  });
}

但是你只能在异步上下文中调用这个函数。大多数现代浏览器都支持顶级等待(在 type=module 的脚本中),但以防万一,您可能希望将其包装在一个函数中:

(async () => {
  const heightOfImage = await getImgSize("...");
})();

【讨论】:

    猜你喜欢
    • 2020-07-29
    • 2017-11-08
    • 2021-03-04
    • 2022-01-14
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    相关资源
    最近更新 更多