【问题标题】:recursively call a JS function that uses promises (chunk write)递归调用使用 Promise 的 JS 函数(块写入)
【发布时间】:2016-12-02 23:05:35
【问题描述】:

我正在尝试编写一个函数,该函数递归调用自身以将 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;
    }

【问题讨论】:

标签: javascript promise


【解决方案1】:

当你调用另一个方法时,返回返回的 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);
            });   
    }
}

【讨论】:

  • 完美 - 这是缺少的链接!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 2020-02-10
  • 2017-03-25
  • 1970-01-01
  • 2021-02-03
相关资源
最近更新 更多