Search code examples
typescript

Typescript Promise file upload


Hi every one im trying to open a dialog window after every file is uploaded to a server. However the window is opening first before all the files are uploaded. Can someone please tell me what I am doing wrong?

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

Solution

  • The issue with your code is that you resolve the promise on first fileUpload and also you don't wait until upload finishes

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