0

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;
};
  • What exactly is the error or problem you're running into? The code looks OK-ish at a glance – CertainPerformance Aug 26 '19 at 01:46
  • thank you for your comment. Even if this was executed, the result was not entered in the result, and length 0 remained. –  Aug 26 '19 at 01:47
  • If the problem is that `result` looks empty, you aren't waiting for it to be populated - use `Promise.all` to wait for all Promises to resolve first – CertainPerformance Aug 26 '19 at 01:53
  • ???, but I do know `xhr.status === 200` `xhr.onload` every time. xhr `load` assumes `xhr.readyState === 4 && xhr.status === 200` already. You would have to run `xhr.onerror` to get a load error, or run those the status test onloadend instead. – StackSlave Aug 26 '19 at 01:57

0 Answers0