首页 > 解决方案 > `await image.onload;` 是如何工作的?onload 为空,但等待等待 onload

问题描述

我正在寻找一种获取图像大小的方法。

我了解到 Promise 和 async/await 可以在 image.onload 中使用。

然而,与许多示例不同的是,我发现它只需在代码中等待空状态 onload 即可工作。

为什么这很好用?

这是我的代码

  const base64 = reader.result;
  reader.onloadend = async () => {
        if (base64) {
          let img = new Image();
          img.src = base64.toString();
          await img.onload; // <-- null, Here's my question
          // img succesfully loaded.
        });
   ...
}

添加

正常使用方法:

const base64 = reader.result;
  if (base64) {
  let img = new Image();
  img.src = base64.toString();
  img.onload = async () => {
    // setState or Do something.
  };

但是我没有指定任何回调方法,而是等待图像加载完毕。

我想知道为什么当 onload 为空时你在等我。

标签: javascriptreactjstypescriptimageonload

解决方案


推荐阅读