簡體   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