简体   繁体   中英

Lag by taking an instance of an array using es6

I got an empty array while I'm logging for an instance of an array!

  onSelectMultipleImage = (event): Promise<any> => {
    return new Promise(resolve => {
      const files = <File[]>event.target.files;
      let file: File;
      let counter = -1;
      const response = [];
      while (file = files[++counter]) {
        const reader: FileReader = new FileReader();
        reader.onload = ((f) => {
          return () => {
            response.push({
              file: f,
              base64: reader.result
            })
          }
        })(file);
        reader.readAsDataURL(file);
        console.log(counter);
        if(counter == files.length -1) {
          console.log('inside the while');
          resolve(response);
        }
      }
    });
  };

  onImagesSelect = async (event: Event) => {
    this.newImages = await this.helper.onSelectMultipleImage(event) || [];
    console.log(this.newImages, "Original"); // [file: File, base64: "base 64 long string..."]        
    console.log([...this.newImages],"instance"); // [] empty array
    setTimeout(() => {console.log([...this.newImages, 'instance'])}, 2000); // [file: File, base64: "base 64 long string..."]
  }

So why I'm getting the presented result? It's something causing by the base64 presented inside the array? if yes what is the solution?

It doesn't wait reader.onload to be completed. So resolve(response) is called before response.push .

You can create a promise to read one file and return them with Promise.all like following code.

readFile = (file: File): Promise<any> => {
  return new Promise(resolve => {
    const reader: FileReader = new FileReader();
    reader.onload = (f) => {
      resolve({
        file: f,
        base64: reader.result
      });
    };
    reader.readAsDataURL(file);
  })
}

onSelectMultipleImage = (event): Promise<any> => {
  const files = <File[]>event.target.files;
  return Promise.all(files.map(file => readFile(file)));
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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