I have an area for uploading files, with the ability to drag and drop multiple files, when uploading, I need to add the position of each file to the request(filePosition). The file position is the length of the array that is filled in then after the files are loaded. The question is how to make the next fetch call run only after the file object is added to the array
let materialFiles: [{
lang: 'en',
files: {
restFiles: []
}
}, ],
let files = e.target.files || e.dataTransfer.files;
let allowFiles = this.validateFiles(e, files, curObj);
Array.from(allowFiles).forEach(file => {
attachThumbnail(curObj, file, e.target)
});
async attachThumbnail(curObj, file, eventTarget) {
let index = this.formData.materialFiles.findIndex(item => item.lang === curObj.lang);
let filePosition = curObj.files.restFiles.length;
this.uploadFile(curObj, file, 'rest', filePosition)
.then(response => response.json())
.then(data => {
this.formData.materialFiles[index].files.restFiles.push({
name: data.fileName,
id: data.id
})
})
.catch(error => {
console.log(error)
});
},
uploadFile(curObj, file, type, position) {
let formData = new FormData(),
data = {
document: file,
type: type,
lang: curObj.lang,
position: type === 'rest' ? position : 0
}
for (let key in data) {
formData.append(key, data[key]);
}
fetch('/api/material_media', {
method: 'POST',
body: formData,
})
},
In my case, fetch is performed first and only then push to then occurs. It is necessary that first go to then and add an object to the array (so that its length changes) and then fetch is called for the next file.