繁体   English   中英

如何从此异步 function 返回值? img.onLoad 事件

[英]how to return value from this async function? img.onLoad event

如何从 function getImgSize(imgSrc)返回height 请记住onload()是异步的。

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

  img.onload = function() {
    const height = img.height;
  }
  img.src = url;
}

您可以将其包装在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
    };
  });
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM