打字稿承诺文件上传

时间:2018-08-27 12:35:07

标签: typescript

每个文件上载到服务器后,我都想打开一个对话框。但是,在所有文件上传之前,该窗口首先打开。有人可以告诉我我在做什么错吗?

public UploadAll() {

    this.doAsyncTask().then(() => 

    this.dialog.open(DialogOverviewExampleDialog, {
        height: '200px',
        width: '300px',
    }));
}

doAsyncTask() {

    var promise = new Promise((resolve, reject) => {
    this.fileUploads.forEach((fileUpload) => {
        fileUpload.upload();
        resolve();
    });
});
return promise;
}

1 个答案:

答案 0 :(得分:2)

您的代码存在的问题是您首先解决了fileUpload的承诺,而且也不必等到上传完成

public UploadAll() {

    this.doAsyncTask().then(() => 

    this.dialog.open(DialogOverviewExampleDialog, {
        height: '200px',
        width: '300px',
    }));
}

doAsyncTask() {

 return Promise((resolve, reject) => {
    const promises : Array<Promise> = [];
    this.fileUploads.forEach((fileUpload) => {
           promises.push(fileUpload.upload());
    });
    Promise.all(promises)
         .then(() => resolve())
         .catch((err) => reject(err));
  });
}