Chrome应用,javascript,fileSystem - > createWriter - > onwriteend被调用两次而不是一次(?)

时间:2016-09-26 13:20:48

标签: javascript javascript-events filesystems google-chrome-app

我有(改编)以下代码

    function saveFiles(saving_dir, content, name) {
      var i = 1;
      return new Promise(function(resolve) {
        chrome.fileSystem.getWritableEntry(saving_dir, function(entry) {
          entry.getFile(name, {
            create: true
          }, function(entry) {
            entry.createWriter(function(writer) {
              writer.onwrite = function() {
                writer.onwrite = null;
                writer.truncate(writer.position);
              };
              writer.onwriteend = function(e) {
                console.log(i)
                i++;
                console.log('written! "' + name + '"')
                // resolve();
              };
              writer.onerror = function(e) {
                console.log('failed! "' + name + '"');
                console.log(e);
              };

              var blob = new Blob([JSON.stringify(content)], {
                type: 'text/javascript'
              });
              writer.write(blob);
            }, function(e) {
              trace.innerText = 'error is ' + e;
              console.log(e);
            });
          });
        });
      });
    }

    saveFiles('/', 'hola', 'delete.txt');

我不知道为什么这会两次执行onwriteend事件,而console.log(i)提供12

如果我在其间添加日志,除事件外,一切都会被调用。有提示吗?

1 个答案:

答案 0 :(得分:1)

您在write听众中触发了truncate,然后是onwrite

根据last public draft of the spec,您对truncate的来电也会触发writeend事件。