I have an array of images which I iterate and upload each to a remote server. Once the file is uploaded I use the result to get the file name and push to another array.
The problem I'm having is that not all results are being pushed to the array. I'm trying to construct an array with the results for all images uploaded. The following code executes lastTask
before the forEach
loop is finished:
/**
* Upload picture
*/
$scope.upload = function () {
var token = window.localStorage.getItem('yourTokenKey');
var defer = $q.defer();
var promises = [];
var options = {
fileKey: "image",
fileName: " test.png",
chunkedMode: true,
mimeType: "image/png",
headers: {'x-auth-token': token}
};
function lastTask() {
alert(promises);
$scope.images = [];
$scope.hide();
$scope.showAlert();
$scope.putQc();
alert('finish').then(function () {
defer.resolve();
});
}
angular.forEach($scope.images, function (image) {
$cordovaFileTransfer.upload("http://server.com/file/upload", image, options).then(function (result) {
// Success!
promises.push(result.response + '.jpg');
alert(JSON.stringify(result));
console.log("SUCCESS: " + JSON.stringify(result.response));
// Error
}, function (err) {
alert(JSON.stringify(err));
console.log("ERROR: " + JSON.stringify(err));
// constant progress updates
}, function (progress) {
$scope.show();
});
});
$q.all(promises).then(lastTask);
return defer;
};