简体   繁体   English

通过使用es6获取数组实例来延迟

[英]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? 这是由数组内显示的base64引起的吗? if yes what is the solution? 如果是,解决方案是什么?

It doesn't wait reader.onload to be completed. 它不等待reader.onload完成。 So resolve(response) is called before response.push . 因此resolve(response)response.push之前被调用。

You can create a promise to read one file and return them with Promise.all like following code. 您可以创建一个承诺来读取一个文件并通过Promise.all将它们返回,就像下面的代码一样。

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)));
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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