In an AngularJS app I am developing, I'm attempting to process multiple uploaded files asynchronously in order to prepare them for a routine that adds them to a SuiteCRM instance. Overall, the code is bug free but I'm finding that the deferred calls are getting executed one after another and not passing the result to the awaiting script until all promises are resolved. Perhaps someone could help me out with how to chain these in order to get the result I want?
function fileReader(file) { // perform async operation
var deferred = $q.defer();
var reader = new FileReader();
reader.onload = function () {
deferred.resolve(reader.result.replace(/^(.*),/g, ""));
};
reader.readAsDataURL(file);
return deferred.promise;
}
$scope.uploadFiles = function () {
console.log('Starting uploads');
$scope.uploadClicked = true;
$scope.uploadProgress = {};
$applicationID = $('#application_id').val();
var tmpMerchData = SessionService.getMerchantData();
var isoID = SessionService.getISOID();
if ($scope.fileList && $scope.fileList.length) {
var $myFiles = $scope.fileList;
for (var f = 0; f < $myFiles.length; f++) {
var thisFile = $myFiles[f];
console.debug(thisFile);
fileReader(thisFile.file).then(function (result) {
ApplicationFactory.createNewUploadedDocument(thisFile, thisFile.templatetype, result, thisFile.description, $scope.userID, tmpMerchData.id, $applicationID, isoID).then(
function successCallback(response) {
if (response.data.status === 1) {
console.log("Document creation succeeded");
$scope.uploadProgress = {
'progress': 100,
'index': f
};
} else {
console.log("Document creation failed");
}
}, function errorCallback(response) {
console.debug("Error returned from createNewUploadedDocument", response);
});
});
}
}
};
So, you see, I need the FileReader to process the file, return the file's contents in order to pass it on to the createNewUploadedDocument function for each of the f (files) in my $scope.fileList. NGF's multiple files option is not available to me because each of these files has a specific template type and description.
Any help you can provide or suggest would be greatly appreciated.
EDIT - I have read this Chaining multiple promises created through for loop and this angular $q, How to chain multiple promises within and after a for-loop but neither are providing any usable feedback for my specific situation. I understand that promises can be nested and combined using $q.all but can they still provide resulting data to one another? My inner method is a call to a REST API - not that it makes any difference - but I do need the result of the FileReader promise in order to call it.