【问题标题】:writing text file in suspend state event handler in windows 8 html5在 Windows 8 html5 中的挂起状态事件处理程序中写入文本文件
【发布时间】:2013-05-20 21:21:19
【问题描述】:

我正在尝试在触发暂停事件时写入文本文件,即在 winjs.application.oncheckpoint 事件处理程序中。 我正在将我的对象写为 JSON 文本。 这是代码:

        applicationData.localFolder.createFileAsync("dataFile.txt", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (sampleFile) {
            var stringData = "";
            var i;
            for (i = 0 ; i < myData.objData.length - 1 ; i++) {
                stringData += '{"title":"' + myData.objData[i].title + '","challange":"' + myData.objData[i].challange + '"},\n';
            }
            stringData += '{"title":"' + myData.objData[i].title + '","challange":"' + myData.objData[i].challange + '"}';
            stringData = "[" + stringData + "]";
            return Windows.Storage.FileIO.writeTextAsync(sampleFile, stringData);
        }).done(function () { });

但 Windows 应用程序在将任何内容写入文本文件之前关闭。 我调用了 args.setPromise() 并将上面的代码作为函数参数传递,但同样的问题仍然存在。

PS:我不知道如何正确地异步执行它。 请帮忙。

【问题讨论】:

    标签: javascript html windows-8 winjs filewriter


    【解决方案1】:

    只要event.setPromise(applicationData.localFolder.createFileAsync ...)

    然后暂停将等到您的承诺完成。删除.done

    【讨论】:

      【解决方案2】:

      就像 Phil 评论的那样,删除 .done() 将修复它。

      这是因为done() 不返回任何内容,而then() 返回链式承诺。这就是什么都没有被调用的原因。

      还建议您在应用程序数据发生更改时或每隔一段时间保存应用程序数据,而不是等待挂起事件保存所有内容。暂停事件给出 5 秒的时间。否则,应用程序将按照msdn documentation here 终止。

      “如果应用程序在 5 秒内没有从挂起事件中返回,Windows 将假定应用程序已停止响应并终止它”

      app.oncheckpoint = function (args) {
      app.sessionState.history = nav.history;
      
      args.setPromise(Windows.Storage.ApplicationData.current.localFolder.createFileAsync
          ("dataFile.txt", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (sampleFile) {
              var stringData;
              // code to set stringData.
      
              return Windows.Storage.FileIO.writeTextAsync(sampleFile, stringData);
          }));
      

      };

      【讨论】:

      • 工作正常,感谢您的帮助。但现在如果我关闭应用程序并再次快速打开它会导致数据丢失。我想我应该在数据更改后立即写一个文件。
      • 是的。将其保存到文件中,并在此类 UI 操作中显示用户进度(进度环)应该会更好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      相关资源
      最近更新 更多