!!! this question is not about how to pass an array of promises to the when
function since neither file
method nor onload
return promises, its not a duplicate
I have a custom method that executes async functions which DO NOT return promises. My custom method does return a promise. What is the correct way to implement the functionality - using timeout like in example 1 or checking for equality in the callback function like in example 2?
EXAMPLE1:
getAllFiles: function () {
var def = $.Deferred();
var files = [];
fileEntries.forEach(function(fileEntry){
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onload = function (e) {
files.push({
name: fileEntry.fullPath,
content: e.target.result
});
};
reader.readAsArrayBuffer(file);
});
});
//this resolves the deffered
var interval = setInterval(function(){
if (files.length === fileEntries.length) {
def.resolve(files);
clearInterval(interval);
}
}, 1000);
return def.promise();
}
EXAMPLE 2
getAllFiles: function () {
var def = $.Deferred();
var files = [];
fileEntries.forEach(function(fileEntry){
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onload = function (e) {
files.push({
name: fileEntry.fullPath,
content: e.target.result
});
//this resolves the deffered
if (files.length === fileEntries.length) {
def.resolve(files);
clearInterval(interval);
}
};
reader.readAsArrayBuffer(file);
});
});
return def.promise();
}