As shown below, it is an array in attachfile.I want to call two functions with forEach using the array.I want to process this array with forEach, but I can't. I would appreciate any advice.I want to put the result in the result
let result = [];
let attachFile = [
{
contentType: "image/png",
fileKey: "1234XXXXXXXXXXXXXXXXXXXXXXXXX",
name: "download (1).png",
size: "14046"
},
{
contentType: "image/png",
fileKey: "12345XXXXXXXXXXXXXXXXXXXXXXXX",
name: "download (1).png",
size: "14046"
}
];
attachFile.forEach(function (value) {
return fileDownload(value.fileKey).then(function (resp) {
result.push(fileUpload(value.name, value.contentType, resp));
});
});
There are two functions.
function fileDownload(fileKey) {
return new Promise(function (resolve, reject) {
var url = xxxxx.url('/k/v1/file', true) + '?fileKey=' + fileKey;
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.responseType = 'blob';
xhr.onload = function () {
if (xhr.status === 200) {
// successful
resolve(xhr.response);
} else {
// fails
reject(Error('File download error:' + xhr.statusText));
}
};
xhr.onerror = function () {
reject(Error('There was a network error.'));
};
xhr.send();
});
}
function fileUpload (fileName, contentType, data) {
let blob = new Blob([data], { type: contentType });
let formData = new FormData();
formData.append("__REQUEST_TOKEN__", XXXXX.getRequestToken());
formData.append("file", blob, fileName);
const xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", encodeURI('/k/v1/file.json'), false);
xmlHttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlHttp.responseType = 'multipart/form-data';
xmlHttp.send(formData);
return JSON.parse(xmlHttp.responseText).fileKey;
};