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