I have an ionic (v1) project that uses angular and cordova.
I am looping over an array of file names and appending each file data in a FormData
object, which has to be uploaded to server.
For reading the file data, Cordova/HTML5
provides some methods which are asynchronous. I am using angular's $q
promise for calling these methods.
Then I want to use $q.all
to wait till all the promises are resolved and start the upload.
But the promises are never getting resolved and the resolved function block inside $q.all(promises).then
is never getting called.
Strangely if I reject the promise instead of resolving it with deferred.reject
it calls the error method of $q.all
.
How do i resolve the promise?
Here is the code:
//Inside a controller
var promises = [];
for (var key in $scope.rArray) {
if ($scope.rArray.hasOwnProperty(key)) {
var deferred = $q.defer();
var tmpFile = $scope.rArray[key];
var i = cordova.file.externalRootDirectory + "/" + tmpFile;
window.resolveLocalFileSystemURL(i, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
console.log('onloadend callled');
var fileBlob = new Blob([this.result], { type:file.type});
fd.append('file', fileBlob,file.name);
deferred.resolve(fd); //if reject here it is reflected
//$rootScope.$apply(). tried this too
};
reader.readAsArrayBuffer(file);
}, function(e) {
console.log('error getting file', e);
deferred.reject(e);
});
}, function(e) {
console.log('Error resolving fs url', e);
deferred.reject(e);
});
promises.push(deferred.promise);
}
};
$q.all(promises).then(function (dataAr) {
console.log('promises resolved..'); //NEVER CALLED
var request = new XMLHttpRequest();
request.open('POST', ENV.baseUrl+"/st/st");
request.send(fd);
}, function errorfn(err) {
console.error(JSON.stringify(err));
})