The img.onload nested in fileReader.onload cannot get external variables (async, closures).

the code is as follows:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <input type="file" onchange="fileChoosed(event)">
  <img id="a">
  <script>
    function fileChoosed(event) {
      console.log("aa");
      let file = event.target.files[0],
        fileName = file.name,
        img = document.getElementById("a"),
        fr = new FileReader(),
        ts = this;
      fr.addEventListener("load", () => {
        let blob = "a";
        console.log(fileName, img, blob); //
        img.onload = (img, blob, fileName) => {
          debugger;
          view.insertPicture(img, blob, fileName); //
        };
        img.src = fr.result;
      });
      fr.readAsDataURL(file);
    }
  </script>
</body>

</html>

after searching for a long time, I couldn"t find the reason. Ask for help

Mar.04,2021

which tutorial or document of img.onload tells you that it is referenced

if you talk to yourself, add three parameters to it.

img.onload is called by whom, it is necessary to find out

first.
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <input type="file" onchange='fileChoosed(event)'>
  <img id='a'>
  <script>
    function fileChoosed(event) {
      console.log('aa');
      let file = event.target.files[0],
        fileName = file.name,
        img = document.getElementById('a'),
        fr = new FileReader(),
        ts = this;
      fr.addEventListener("load", () => {
        let blob = 'a';
        console.log(fileName, img, blob); //
        img.onload = () => { //
          debugger;
          console.log(fileName, img, blob); 
        };
        img.src = fr.result;
      });
      fr.readAsDataURL(file);
    }
  </script>
</body>

</html>
Menu