2016-12-02 13 views
2

ブロブをディスクにチャンクで書き込むために再帰的に呼び出す関数を作成しようとしています。再帰が機能し、チャンクが進行している間に、関数が自身の約束をインスタンス化し、書き込みが完了したときに戻る必要があるため、返される約束をどのように処理するのかがわかりません。 writeFile2は最初にisAppend = falseを指定して呼び出し関数から呼び出されます。は、約束(チャンク書き込み)を使用する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

[延期された反パターン](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

関連する問題