【问题标题】:Windows Universal App - Javascript - File IO - No ResponseWindows 通用应用程序 - Javascript - 文件 IO - 无响应
【发布时间】:2017-08-18 15:54:46
【问题描述】:

我有一个文件保存功能:

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

};

那我这样称呼它,取决于myfile.txt是否存在:

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

我做错了什么?

注意:如果我使用localFolder.getFileAsync('myfile.txt').done( 而不是localFolder.getFileAsync('myfile.txt').then(,则会引发错误,指出文件不存在(但我知道它存在)。

【问题讨论】:

    标签: javascript file-io uwp win-universal-app


    【解决方案1】:

    thendone 方法之间存在一些差异。其中之一是

    then 函数中未处理的异常被静默捕获作为 Promise 状态的一部分,但 done 函数中未处理的异常是抛出。这两个函数都可以处理作为 Promise 状态的一部分传递给它们的异常。

    对于GetFileAsync(String) 方法,只有当该方法成功完成时,它才会返回代表指定文件的StorageFile。如果没有这样的文件,它会抛出一个错误。所以当你使用 done 而不是 then 时,你会得到错误。

    为了解决这个问题,我们可以修改如下代码,因为这两个函数都可以处理异常。

    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 来检查文件是否在本地文件夹下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 2015-09-20
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 2016-02-16
      • 1970-01-01
      相关资源
      最近更新 更多