Jan 20

Windows 8 adventures: error handling and the async pattern

Posted in Windows8      Comments Off on Windows 8 adventures: error handling and the async pattern

In the previous post, we’ve started looking at the async pattern in Windows 8 Metro apps developed with JavaScript. By now, you know that all async operations are wrapped in Promise objects which you can use to be notified when that operation has ended (besides other interesting things!). We’ve also seen how we can “improve” the code readability associated with several async operations which are executed in chain.

What I didn’t mention at the time is that the then method expects three parameters (all functions). Besides the success function, you can also pass two other functions which will be called, respectively, for reporting an error and for reporting progress. If you follow my previous advice and return new Promises from the then method, then you can get “global” error handling by adding a final then method which defines the global method function. Here’s an improved version of the createFolderAndFile function:

function createFolderAndFile() {
    //create new folder inside temp folder
    var tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;
    .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 () {
            return stream.flushAsync()
            .then(function () {}, function () { }); }); })
    .then(null, function (err) { //handle error here! });;

Notice that there’s a slight change and we’re returning the result of the storeAsync().then call so that all eventual errors can be handled in the error function passed to the last then method call. You can test this behaviour by adding throw statements in several places in the previous code and by setting a breakpoint inside that anonymous error function.

And that’s all for now. Stay tuned for more.