等待循环执行,然后返回值

时间:2018-08-09 14:29:49

标签: angular ionic-framework

如何在上传之前等待所有文件加载。

我正在使用Ionic 3和Angular 5尝试从iOS和Android上传文件。

我有一个存储在存储器中的文件列表。我检索文件列表,遍历它们,读取文件,然后尝试将每个文件添加到formData中。该函数返回null,因为它没有等待循环完成。我该如何解决?

file-provider.ts

import {File} from '@ionic-native/file';

readonly directory = this.fileCtrl.dataDirectory;

constructor
(
private fileCtrl: File,
private storage: StorageProvider,
)

getFilesByFolderID(folderID): any {
    let formData = new FormData();
    let missingFiles = [];
    const path = `${this.directory}${folderID}`;
    // i have the names of the file and information about them in local storage 
    return this.storage.getFiles(folderID).then(data => {
      const files = data.files
      files.forEach(file => {
        this.fileCtrl.resolveDirectoryUrl(path).then(url => {
          this.fileCtrl.getFile(url, file.uniqName, {create: false}).then(entry => {
            entry.file( f => {
              formData.append('data', f, file.name);
              formData.append('type', file.type);
              formData.append('size', file.size);
              formData.append('icon', file.icon);
            });

          }).catch(err => {
            missingFiles.push(file.name);
            console.log("ERROR ", JSON.stringify(err));
          })
        }).catch(err => this.handleFileError(err));
      });
      // This is always empty
      return formData;
      });
}

2 个答案:

答案 0 :(得分:0)

您应该能够等待循环中的所有promise都可以解决,然后在完成后返回。这可能需要调整,但应该可以满足您的目的。

getFilesByFolderID(folderID): any {
    let formData = new FormData();
    let missingFiles = [];
    let promises: any[] = []
    const path = `${this.directory}${folderID}`;
    // i have the names of the file and information about them in local storage 
    this.storage.getFiles(folderID).then(data => {
      const files = data.files
      files.forEach(file => {
        let promise = this.fileCtrl.resolveDirectoryUrl(path).then(url => {
          this.fileCtrl.getFile(url, file.uniqName, {create: false}).then(entry => {
            entry.file( f => {
              formData.append('data', f, file.name);
              formData.append('type', file.type);
              formData.append('size', file.size);
              formData.append('icon', file.icon);
            });

          }).catch(err => {
            missingFiles.push(file.name);
            console.log("ERROR ", JSON.stringify(err));
          })
        }).catch(err => this.handleFileError(err));
        promises.push[promise];
      });
      });

      //this should wait for all promises to resolve
      Promise.all(promises).then(()=>{
        return formData;

      })



}

答案 1 :(得分:0)

如果您将return formData直接放在此代码之后,是否可行:

entry.file( f => {
    formData.append('data', f, file.name);
    formData.append('type', file.type);
    formData.append('size', file.size);
    formData.append('icon', file.icon);
});
return formData;

此外,调用方法应如下所示,因为此方法返回了Promise:

getFilesByFolderID(2).then((hi) => {console.log(hi)})

您可能还想阅读Promise.all()