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

时间:2019-05-27 20:31:31

标签: javascript angular ecmascript-6 base64 lag

我在记录数组实例时得到了一个空数组!

  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..."]
  }

那么为什么我要得到呈现的结果?这是由数组内显示的base64引起的吗?如果是,该怎么解决?

1 个答案:

答案 0 :(得分:0)

它不会等待reader.onload完成。因此resolve(response)response.push之前被调用。

您可以创建一个承诺来读取一个文件,并像下面的代码一样用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)));
};