1

I have a set of inputs and images:

enter image description here

I am looping through the divs to get the names and the photos:

$('.subCats').each(function () {
    let id   = genRandomStr(),
        name = $(this).find('input.subCatName').val();

    if (name.length > 0) {
        dataObj['subCats'].push({
            'id'   : id,
            'name' : $(this).find('input.subCatName').val()
        });

        $(this).find('.media-list img').each(function () {
            if ($(this).data('stored') === false)
                urlToFile($(this).attr('src'), $(this).attr('title'), 'image')
                    .then(function (file) {
                        data.append('subCatsPhotos[' + id + ']', file);
                });
        });
    }

});

I have an AJAX request just after but the problem is the request is executing before the image has been appended to the FormData.

This is the code that is converting the image to a file object:

function urlToFile(url, filename, mimeType) {
    return (fetch(url)
        .then(function(res){return res.arrayBuffer();})
        .then(function(buf){return new File([buf], filename,{type:mimeType});})
);

}

I have looked at these solutions but I am struggling to adapt them to my code.

Jolan
  • 681
  • 12
  • 39

1 Answers1

1

You could keep track of how many appends have happened:

let appended = 0;
const elements = [1,2,3,4,5];
elements.forEach(element => {
    // Do whatever with element
    // Using setTimeout to emulate .then()
    setTimeout(() => {
        console.log('Appended', element, 'at', Date.now());
        if (++appended === elements.length) {
            console.log('Appended all!');
            // Do your AJAX request
        }
    }, 100 * Math.random());
});

Alternatively, if you can use .map instead of .each:

const elements = [5,4,8,7,5,4];
const promise = Promise.all(elements.map(element => {
    // Some promise
    return new Promise(r => setTimeout(() => {
        console.log('Appended', element, 'at', Date.now());
        r();
    }, Math.random() * 100));
}));
promise.then(() => {
    console.log('Appended all!');
});
Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31