From e6d3156dd421eb181af5119bd9c69130723139eb Mon Sep 17 00:00:00 2001
From: Patrizio Bekerle <patrizio@bekerle.com>
Date: Fri, 20 Mar 2020 14:03:45 +0100
Subject: [PATCH] Upload files in serial instead of parallel to not overburden
 servers (VPU/Middleware/API#40)

---
 packages/file-handling/src/vpu-fileupload.js | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/packages/file-handling/src/vpu-fileupload.js b/packages/file-handling/src/vpu-fileupload.js
index eceb803b..e1f68a8e 100644
--- a/packages/file-handling/src/vpu-fileupload.js
+++ b/packages/file-handling/src/vpu-fileupload.js
@@ -90,9 +90,17 @@ class VPUFileUpload extends VPULitElement {
         this.handleFiles(this.shadowRoot.querySelector('#fileElem').files);
     }
 
-    handleFiles(files) {
+    async asyncForEach(array, callback) {
+        for (let index = 0; index < array.length; index++) {
+            await callback(array[index], index, array);
+        }
+    }
+
+    async handleFiles(files) {
         console.log('handleFiles: files.length = ' + files.length);
-        ([...files]).forEach(this.uploadFile.bind(this))
+
+        // we need to wait for each upload until we start the next one
+        this.asyncForEach(files, async (file) => this.uploadFile(file));
     }
 
     sendFinishedEvent(response, file) {
@@ -109,13 +117,13 @@ class VPUFileUpload extends VPULitElement {
         });
     }
 
-    uploadFile(file) {
+    async uploadFile(file) {
         let url = this.url;
         let formData = new FormData();
 
         formData.append('file', file);
 
-        fetch(url, {
+        await fetch(url, {
             method: 'POST',
             headers: {
                 'Authorization': 'Bearer ' + window.VPUAuthToken,
-- 
GitLab