I am currently working on developing a hybrid mobile app using angularJS and ionic as a mobile developer.
I am facing an issue with an async function where the value has to be returned after all conversions and mappings are completed. However, I keep getting null values because the conversion process takes longer than the mapping process.
I want to ensure that the mapping runs only after the conversion is done.
Below is my service code:
angular.module('file.service', ['ionic'])
.factory('fileService', ['$q', function($q) {
var factory = {};
factory.getContentImageFix = function(fileParsing){
var contentImg = [];
for(var i = 0; i < fileParsing.length; i++){
convertFileToDataURLviaFileReader(fileParsing[i].fullpath, function(base64Img){
contentImg.push({
image: base64Img,
width: 400
});
});
}
return $q.all(contentImg);
}
function convertFileToDataURLviaFileReader(url, callback){
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
}]);
And here is how my controller looks like:
angular.module('scan.module’, ['ionic'])
.controller('scanController’, [‘fileService’, function(fileService) {
var fileParsing = [
{
“name”:”a.jpg",
"fullpath”:”[PATH]/a.jpg"
},{
"name”:”b.jpg",
"fullpath":"[PATH]/b.jpg"
}
];
var contentImg = fileService.getContentImageFix(fileParsing);
console.log(JSON.stringify(contentImg)); //it currently returns an empty array
}]);
I am not very familiar with the concept of promises. Can someone guide me on how to solve this async problem?
Thank you.