I am trying to write a function that recursively calls itself to write a blob to disk in chunks. While the recursion works and the chunks progress, I'm messing up on how to handle the return promises as the function instantiates its own promise and needs to return when the write is complete. writeFile2 is first called from the invoking function with isAppend=false.
function writeFile2( path, file, blob, isAppend)
{
var csize = 4 * 1024 * 1024; // 4MB
var d = $q.defer();
console.log ("Inside write file 2 with blob size="+blob.size);
// nothing more to write, so all good?
if (!blob.size)
{
// comes here at the end, but since d is instantiated on each
// call, I guess the promise chain messes up and the invoking
// function never gets to .then
console.log ("writefile2 all done");
d.resolve(true);
return d.promise;
}
// first time, create file, second time onwards call append
if (!isAppend)
{
$cordovaFile.writeFile(path, file, blob.slice(0,csize), true)
.then (function (succ) {
return writeFile2(path,file,blob.slice(csize),true);
},
function (err) {
d.reject(err);
return d.promise;
});
}
else
{
$cordovaFile.writeExistingFile(path, file, blob.slice(0,csize))
.then (function (succ) {
return writeFile2(path,file,blob.slice(csize),true);
},
function (err) {
d.reject(err);
return d.promise;
});
}
return d.promise;
}