Javascript 递归调用使用承诺的JS函数(区块写入)

Javascript 递归调用使用承诺的JS函数(区块写入),javascript,promise,Javascript,Promise,我正在尝试编写一个递归调用自身的函数,将blob以块的形式写入磁盘。在递归工作和块处理过程中,我把如何处理返回承诺弄得一团糟,因为函数实例化了自己的承诺,并需要在写入完成时返回。writeFile2首先从调用函数调用,isAppend=false function writeFile2( path, file, blob, isAppend) { var csize = 4 * 1024 * 1024; // 4MB var d = $q.defer();

我正在尝试编写一个递归调用自身的函数,将blob以块的形式写入磁盘。在递归工作和块处理过程中,我把如何处理返回承诺弄得一团糟,因为函数实例化了自己的承诺,并需要在写入完成时返回。writeFile2首先从调用函数调用,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;
    }

当您调用另一个方法时,返回所返回的承诺,而不是您自己的。当没有工作要做时,回报你自己的承诺

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);
            });   
    }
}

完美-这是丢失的链接!避开这个!