如何等到 image.src 在 image.onload 事件函数中设置?

How to wait until image.src is set in an image.onload event function?

在我的浏览器javascript 中,对于新的 image() 对象,对于 onload 事件,我首先在用户 select 之后设置 image.src 一个图像文件;然后读取图像对象的大小。

但似乎读取发生在正确设置 src 之前。我碰巧找到了两次调用该函数的修复方法。但是这个解决方案似乎是一个非常糟糕的主意。

请让我知道如何以标准方式修复它。我的环境接受 Typescript。

var imgLoaded=false;
 var file = document.getElementById("fileInput").files[0];
      for(let i=0;i<2;i++){    
          call2(file);
         }
      

   function call2(file) {
      var reader = new FileReader();
      reader.readAsDataURL(file);

      reader.onload = function () {
          if(!imgLoaded){ 
              imgLoaded=true;   img.src=(reader.result).toString();}
         else{
        console.log(img.width);
      }}

我自己至少找到了一个更好的解决方案。虽然不知道这个算不算标准


 var file = document.getElementById("fileInput").files[0];
          call2(file);
      

    function call2(file) {
      var reader = new FileReader();
      reader.readAsDataURL(file);

      reader.onload =async function () {
         img.src= await (reader.result).toString();
         console.log(await img.width);
      }}

用一种方法你可以替换 file = document.getElementById("fileInput").files[0];file = event.target.files[0] 并在调用 2 中使用它,您还应该将事件传递给调用 2

例如:在 html 中: <input type="file" onchange="call2(event)" /> ,然后在 js function call2(e){let file = e.target.files[0] ... }