2
我想写一个函数,递归调用自己将块写入磁盘块。虽然递归工作和块进展,但我搞乱了如何处理返回的承诺,因为函数实例化自己的承诺,并且在写入完成时需要返回。首先使用isAppend = false从调用函数调用writeFile2。递归调用使用承诺(块写)的JS函数
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;
}
避免[deferred antipattern](http://stackoverflow.com/q/23803743/1048572)! – Bergi