I need the ajax work synchronously and only display console.log('Downloads finalized!');
when all downloads are finished, but the count++
is not working within the fileTransfer.download
function. Why?
My code:
function getdata()
{
var fileTransfer = new FileTransfer();
var path = cordova.file.dataDirectory;
jQuery.getJSON(MyJSONData, function( data ) {
var count = 0;
jQuery.each(data, function(key, val) {
fileTransfer.download(
MyFileURL,
path+"data/images/"+key+".jpg",
function(theFile) {
console.log('Saved');
count++;
}, null
);
});
while(1)
{
if(count == Object.keys(data).length)
{
console.log('Downloads finalized!');
break;
}
}
}).fail(function() {
console.log('Error');
});
}
I need the ajax work synchronously
No, you need to understand how to use callback functions.
function getdata() {
var fileTransfer = new FileTransfer();
var path = cordova.file.dataDirectory;
jQuery.getJSON(MyJSONData, function(data) {
var count = 0;
jQuery.each(data, function(key, val) {
fileTransfer.download(
MyFileURL,
path + "data/images/" + key + ".jpg",
function(theFile) {
console.log('Saved');
count++;
if (count == Object.keys(data).length) {
console.log('Downloads finalized!');
}
}, null
);
});
}).fail(function() {
console.log('Error');
});
}