2016-12-02 112 views
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; 
    } 
+0

避免[deferred antipattern](http://stackoverflow.com/q/23803743/1048572)! – Bergi

回答

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

完美 - 這是缺少的環節! – user1361529