2017-03-25 3 views
1

は、私は、ファイルの保存機能があります。Windowsのユニバーサルアプリケーション - Javascriptを - - ファイルIO応答なし

function WINJSWrite(file, content) { 
    if (content.length <= 0) { 
     GameConsts.MyAlert("No data to save."); 
    } 

    // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync. 
    Windows.Storage.CachedFileManager.deferUpdates(file); 
    // write to file 
    Windows.Storage.FileIO.writeTextAsync(file, content).done(function() { 
     // Let Windows know that we're finished changing the file so the other app can update the remote version of the file. 
     // Completing updates may require Windows to ask for user input. 
     Windows.Storage.CachedFileManager.completeUpdatesAsync(file).done(function (updateStatus) { 
      if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) { 
       //WinJS.log && WinJS.log("File " + file.name + " was saved.", "sample", "status"); 
      } else { 
       //WinJS.log && WinJS.log("File " + file.name + " couldn't be saved.", "sample", "status"); 
      } 
     }); 
}); 

を};

localFolder.getFileAsync('myfile.txt').then(
     function (file) { 
      // NEVER GETS HERE 
      if (file) { 
       WINJSWrite(file, content); 
      } else { 
       localFolder.createFileAsync("myfile.txt").done(
        function (newFile) { 
         if (newFile) { 
          WINJSWrite(newFile, content); 
         } 
        }); 
      } 
     }); 

しかし、コードが// NEVER GETS HEREになることはありません:次のように

それから私はmyfile.txtが存在するかどうかに応じて、これを呼び出します。

私は間違っていますか?

注:localFolder.getFileAsync('myfile.txt').then(の代わりにlocalFolder.getFileAsync('myfile.txt').done(を使用すると、ファイルが存在しないとのエラーが表示されます(ただし、わかります)。

答えて

2

thendoneの方法にはいくつかの違いがあります。そのうちの一つは、その後、機能で

未処理の例外がは黙って約束の状態の一部としてを撮影していますが、行わ機能で未処理の例外がを投げているということです。どちらの関数も、約束の状態の一部として渡された例外を処理できます。

そしてGetFileAsync(String)方法については、このメソッドが正常に完了した場合にのみ、指定したファイルを表しStorageFileを返します。そのようなファイルがない場合は、エラーが発生します。したがっての代わりにとし、の代わりに使用すると、エラーが発生する可能性があります。

この問題を解決するには、両方の関数が例外を処理できるため、次のようなコードを変更できます。

localFolder.getFileAsync('myfile.txt').done(
    function onComplete(file) { 
     WINJSWrite(file, content); 
    }, function onError() { 
     localFolder.createFileAsync("myfile.txt").done(
      function (newFile) { 
       WINJSWrite(newFile, content); 
      }); 
    }); 

詳細については、Quickstart: Using promisesを参照してください。また、my previous answerを参照して、ファイルがローカルフォルダの下にあるかどうかを確認することもできます。

関連する問題