locked
DataWriter: flushing a stream requires a then call?

    Question

  • Hello guys. I'm using the following code to create a new text file in a temp subfolder:

    function createFolderAndFile() {
        //create new folder inside temp folder
        var tempFolder =
          Windows.Storage.ApplicationData.current.temporaryFolder;
        tempFolder.createFolderAsync("testFolder",
          Windows.Storage.CreationCollisionOption.openIfExists)
            .then(function (folder) {
                return folder.createFileAsync("testFile.txt")
            })
            .then( function (file) {
                return file.openAsync(
                            Windows.Storage.FileAccessMode.readWrite);
            })
            .then( function (dataStream) {
                var stream = dataStream.getOutputStreamAt(0);
                var writer = new Windows.Storage.Streams.DataWriter(stream);
                writer.writeString("Howdy, there!");
                return writer.storeAsync()
                    .then(function () {
                    stream.flushAsync()
                                .then(function () {},function () {});
                    });
            });
    }

    If I remove the .then(function () {},function () {}); instruction from the code, the contents won't get written to the file. Is this a bug? I was under the impression that .then was only required if I needed to be notified when the flush operation has fnished. Comments?

    thanks.


    Luis Abreu
    Thursday, January 19, 2012 2:53 PM

Answers

  • Hi Luis,

     

    The stream is being left open because of the scoping of the stream variable.

    You can solve this by propagating the return of the promise back:

    return stream.flushAsync();

    -Jeff


    Jeff Sanders (MSFT)
    Monday, January 23, 2012 3:55 PM
    Moderator

All replies

  • Are you by chance doing this in a background task?
    Jeff Sanders (MSFT)
    Friday, January 20, 2012 1:23 PM
    Moderator
  • Nop. It's run when the click event of a button is fired:

    WinJS.Utilities.ready(initializeSample, true);
      function initializeSample() {
          document.getElementById("ct").addEventListener("click", createFolderAndFile);
          document.getElementById("ct2").addEventListener("click", readFile);
      }


    Luis Abreu
    Monday, January 23, 2012 11:49 AM
  • Hi Luis,

     

    The stream is being left open because of the scoping of the stream variable.

    You can solve this by propagating the return of the promise back:

    return stream.flushAsync();

    -Jeff


    Jeff Sanders (MSFT)
    Monday, January 23, 2012 3:55 PM
    Moderator