I am trying to implement Uploadcare for multi-image upload, but confused about the code structure. Below code works, but it has two .fail blocks and two .done blocks. Additionally, adding the images to the front-end using $.each() should be done after the group has been saved on the server, while this code executes both simultaneously.
How can this code be improved?
$('button').on('click', function() {
var myDialog = uploadcare.openDialog(null, {
imagesOnly: true, multiple: true, multipleMin: 1, multipleMax: 7
});
myDialog.fail(function(error, fileInfo) {
alert('Upload fialed');
});
myDialog.done(
groupInstance => {
var groupPromise = groupInstance.promise();
var arrayOfFiles = groupInstance.files();
groupPromise.done(function(fileGroupInfo) {
/* Save group to server using Ajax */
uploadGroup(fileGroupInfo.uuid);
});
groupPromise.fail(function(error, fileGroupInfo) {
alert('Upload failed');
});
$.each(arrayOfFiles, function(i, file) {
file.done(function(fileInfo) {
/* Add image to front-end */
});
});
});
return false;
});
And the AJAX function:
uploadGroup = function(imgurl) {
$.post('index.php',
{string:imgurl},
function(data) {
if(data.status=='success') {
alert('success');
}
else {
alert('error');
}
},'json');
};
Also confused about the groupInstance => notation.
It seems arrayOfFiles is an array of promises?
So, you wait for all of them to complete using
$.whenand since you're already using modern javascript, going to add another "oddity" you may not be familiar with
..., but it makes things easier...arayOfFiles......is spread syntax ... sois like
and
function(...fileInfos)is Rest Syntaxis equivalent to
is like