我正在尝试编写一个递归调用自身的函数,以块的形式将blob写入磁盘。当递归工作和块进展时,我正在弄乱如何处理返回promise,因为函数实例化它自己的promise并且需要在write完成时返回。首先使用isAppend = false从调用函数调用writeFile2。
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;
}
答案 0 :(得分:2)
当您调用另一个方法时,返回返回的承诺而不是您自己的承诺。如果没有工作要做,请回复自己的承诺。
function writeFile2( path, file, blob, isAppend) {
var csize = 4 * 1024 * 1024; // 4MB
console.log ("Inside write file 2 with blob size="+blob.size);
// nothing more to write, so all good?
if (!blob.size)
{
// nothing to do, just resolve to true
console.log ("writefile2 all done");
return $q.resolve(true);
}
// first time, create file, second time onwards call append
if (!isAppend)
{
// return the delegated promise, even if it fails
return $cordovaFile.writeFile(path, file, blob.slice(0,csize), true)
.then (function (succ) {
return writeFile2(path,file,blob.slice(csize),true);
});
}
else
{
// return the delegated promise, even if it fails
return $cordovaFile.writeExistingFile(path, file, blob.slice(0,csize))
.then (function (succ) {
return writeFile2(path,file,blob.slice(csize),true);
});
}
}