The documentation for this property has this to say: “Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use Windows Library for JavaScript (WinJS) binding.”

This is rather enigmatic, and the remarks section doesn’t make it much clearer when it says, “Set this property to true to avoid setting the ID of an element automatically.”

This flag was added late in the developer of Windows 8 to get around a memory leak. What was happening before is that WinJS was automatically creating an ID property for all elements involved in data binding, due to the implementation of its binding engine. However, this introduced the leak because the table in which the wwahost.exe process stores such IDs never gets cleaned up.

Generally speaking, apps didn’t depend on these IDs being created, so the WinJS team could have just made the change internally and no one would’ve noticed. However, it did constitute a breaking change so the optimizeBindingReferences flag was added such that an app that did have that dependency could turn it off.

The bottom line is that apps should set this flag to true and leave it set, thereby reducing the app’s memory footprint.


Developers have sometimes asked what apps should do if edge gestures are accidentally invoked, especially for time-sensitive games.

Generally speaking, such apps should pay attention to when they lose focus, which can happen for left/right edge gestures as well as being snapped in favor of another app going into filled view and thus taking the focus. Many games, for instance, pause when snapped (also for playability's sake) and when the charms bar is invoked. The focus events that you can obtain on the top-level app window (e.g. the window object in JavaScript) help you out here.

For top/bottom swipes, these will invoke your own app bar if you provide one (otherwise they have no effect). In this case you can use the beforeShow/beforeHide (WinJS) or Opened/Closed (XAML) events to know when this happens.

More fundamentally, you can also use the events in Windows.UI.Input.EdgeGesture to detect the top/bottom swipes but this is a somewhat lower-level mechanism.

If you haven't seen it, the Designing great games for Windows topic in the docs is also worth a read on many other important points.


If you look around within the WinJS source code files, you’ll see a curious structure for commenting functions. For example, here’s what we see for WinJS.Namespace.define:

function define(name, members) {
    /// <signature helpKeyword=”WinJS.Namespace.define”>
    /// <summary locid=”WinJS.Namespace.define”>
/// Defines a new namespace with the specified name.
    /// </summary>
    /// <param name=”name” type=”String” locid=”WinJS.Namespace.define_p:name”>
    /// The name of the namespace. This could be a dot-separated name for nested namespaces.
    /// </param>
    /// <param name=”members” type=”Object” locid=”WinJS.Namespace.define_p:members”>
    /// The members of the new namespace.
    /// </param>
    /// <returns type=”Object” locid=”WinJS.Namespace.define_returnValue”>
/// The newly-defined namespace.
/// </returns>
/// </signature>
return defineWithParent(global, name, members);

On first glance, you’ll wonder why someone wrote comments like this that are somewhat hard to read. But there is a real purpose: they are what provide IntelliSense data to Visual Studio. That is, because IntelliSense provides you with immediate, in-line documentation when you start writing code, there’s no need for you to look at the source code for functions that you’re consuming to understand how they work. That is, when you type out WinJS.Namespace. and highlight define, you’ll see this pop up:

Intellisense comments 1b

When you continue to enter in define, IntelliSense will pop up the details of the function–you can see that all this information is coming straight from those code comments:

Intellisense comments 2b

There is nothing special about WinJS’ use of these kinds of comments: you can use them in your own code to provide IntelliSense for your own functions. The documentation for doing this is on JavaScript IntelliSense (the overview) and XML Documentation Comments (the details). Here’s a simple example with a function that doesn’t actually do anything meaningful:

function myFunction(item, identifier, options) {
    /// <signature helpKeyword=”MyNamespace.myFunction”>
    /// <summary locid=”MyNamespace.myFunction”>
    /// Does some nifty stuff with the parameters you provide.
    /// </summary>
    /// <param name=”item” type=”Object” locid=”MyNamespace.myFunction_p:item”>
    /// The object to process.
    /// </param>
    /// <param name=”identifier” type=”String” locid=”MyNamespace.myFunction_p:identifier”>
    /// Another parameter that I just made up.
    /// </param>
    /// <param name=”options” type=”Object” locid=”MyNamespace.myFunction_p:options”>
    /// A fine ubiquitous catch-all parameter.
    /// </param>
    /// <returns type=”Object” locid=”MyNamespace.myFunction_returnValue”>
    /// Whatever it is we emit from this function.
    /// </returns>
    /// </signature>
    item.identifier = identifier;
    item.options = options;
    return item;

Now when you start typing out myFunction(, you’ll see this:

Intellisense comments 3

As you enter each parameter, the bold highlight in the first line will change and the description at the bottom will update as well.

The other piece to this story is that if you’re working in another .js file and referencing functions in another, you’ll want to add a reference comment at the top to those other files:

/// <reference path=”ScriptFile1.js” />

This is what tells Visual Studio to scan that other file and extract those IntelliSense comments from it. You’ll see this at the top of the WinJS file ui.js, in fact:

/// <reference path=”ms-appx://Microsoft.WinJS.1.0/js/base.js” />
/// <reference path=”ms-appx://Microsoft.WinJS.1.0/js/ui.js” />


Having covered the basics of WinJS.Class.define in Part 1 and WinJS.Class.derive in Part 2, we come to the third method in WinJS.Class, which is the mix method.

Let’s first see what differentiates a mixin from a derived class. When you derive one class from another, the new class is the combination of the base class’ members and those additional ones you specify for the derivation. In WinJS.Class.derive, you can only specify one base class.

In object-oriented programming, there is the concept of multiple inheritance whereby you can derive a class from multiple base classes. This is frequently used to attach multiple independent interfaces on the new class (it’s used all the time in Win32/COM programming, where an interface is typically defined as a virtual base class with no implementation, and provides the necessary function signatures to the derived class).

As JavaScript itself doesn’t have object-oriented concepts baked into the language–thus necessitating helpers like WinJS.Class.define to play the necessary tricks with prototypes and all that–there isn’t a built-in method to express multiple inheritance.

Hence the idea of a mix or mixin, which isn’t unique to WinJS as evidenced by this article on WikipediaWinJS.Class.mix is basically a way to do something like multiple inheritance by simply mixing together all the instance members of any number of other mixin objects. The description in the documentation for WinJS.Class.mix puts it this way: “Defines a class using the given constructor and the union of the set of instance members specified by all the mixin objects. The mixin parameter list is of variable length.”

So here we see two other differences between a mix and a derivation: a mix does not operate on static members, and does not concern itself with any constructors other than the one given directly to WinJS.Class.mix. (This is also why it’s not true multiple inheritance in the strict object-oriented sense.)

WinJS itself uses the mixing concept for its own implementation. If you look in the docs, you’ll see that there are several mixins in WinJS that you can use yourself: WinJS.UI.DOMEventMixinWinJS.Utilities.eventMixinWinJS.Binding.observableMixin, and WinJS.Binding.dynamicObservableMixin:

  • WinJS.UI.DOMEventMixin contains standard implementations of addEventListener, removeEventListener, dispatchEvent, and setOptions, which are commonly used for custom controls. If you look in the WinJS file ui.js, you’ll see that all the WinJS controls bring this into their mix.
  • WinJS.Utilities.eventMixin is basically the same thing without setOptions, as it is meant for objects that don’t have associated UI elements (it also can’t just use the listener methods on the element in the DOM, so it has its own implementation of these methods).
  • WinJS.Binding.observableMixin adds functionality to an object that makes it “observable” meaning that it can participate in data binding. This consistes of methods bind, unbind, and notify. This is used with the WinJS.Binding.List class.
  • WinJS.Binding.dynamicObservableMixin builds on the idea with methods called setProperty, getProperty, updateProperty, addProperty, and removeProperty. This is helpful for wiring up two-way data binding, something that WinJS doesn’t do itself, but isn’t too hard to pull together. The Declarative binding sample in the SDK shows how.

With events (in the first two mixins), you commonly use WinJS.Utilities.createEventProperties to also create all the stuff a class needs to support named events. createEventProperties returns a mixin object that you can then use with WinJS.Class.mix. For example, if you pass this method an array with just [“statusChanged”] when you’ll get a function property in the mixin names onstatuschanged and the ability to create a listener for that event.

So mixins, again, are a way to add pre-canned functionality to a class, and is a convenient way to modularive code that you’ll use in multiple classes. It’s also good to know that you can call WinJS.Class.mix multiple times with additional mixins, and the results simply accumulate (if there are duplicates, the last member mixed is the one retained).


WinJS.log is an interesting function. Though it's ostensibly part of the WinJS namespace, it's not actually directly implemented within WinJS itself! At the same time, it's used all over the place within the library. Take a look throughout the base.js and ui.js files of WinJS and you'll see many lines like this:

WinJS.log && WinJS.log(safeSerialize(e), "winjs", "error");

That is, WinJS checks if WinJS.log exists, and if so, outputs some log informaion for many different kinds of conditions, primarily error conditions. In other words, this logging will tell you various things that are happening inside WinJS.

To see all that output, though, you need to provide an implementation of WinJS.log yourself; that is, you need to assign some function to this particular variable. That function, as described in the documentation, should accept three parameters:

  1. The message to log
  2. A string with a tag or tags to categorize the message. WinJS always uses "winjs" and sometimes adds an additional tag like "binding" in which case the second parameter is "winjs binding"
  3. A string describing the type of the message. WinJS will use "error", "info", "warn", and "perf"

The simplest way to do this is just map WinJS.log to console.log like so:

WinJS.log = console.log.bind(console);

But this doesn't make for very nice output. For example, this call:

WinJS.log("message", "tag", "type");

Will create the output "messagetagtype" all smooshed together.

To make things a little better, WinJS itself offers a basic implementation of a logger, which is set up by calling WinJS.Utilities.startLog:


Calling this with no parameters, as shown here, sets WinJS.log to a basic function that formats the output a little more nicely using WinJS.Utilities.formatLog (which you can call directly), and outputs the result to the console. So the same test call above will then appear on the console as "type: tag: message".

If you want to filter for specific tags, which is especially useful if you're using WinJS.log in your own code and use tags to identify the module you're calling from, then you can reduce the output. The syntax is to just pass a string with tags separated by spaces. So this code:

WinJS.Utilities.startLog("tag1 tag2");
WinJS.log("message", "tag1", "type");
WinJS.log("message", "tag2", "type");
WinJS.log("message", "tag3", "type");
WinJS.log("message", "tag4", "type");

Will output two lines, "type: tag1: message" and "type: tag2: message" but ignore the other two.

You can actually do much more with that one parameter by passing an object that specified additional options, such as filtering the type and so forth. See the WinJS.Utilities.startLog documentation for details.

Note also that if you call WinJS.Utilities.startLog multiple times, it aggregates the tags you're using. This means you can call it from different modules where each module starts logging for itself.

When you're done logging, you can call WinJS.Utilities.stopLog, which just calls delete WinJS.log. This is an all-or-nothing call, though–you can't remove individual tags from the logging.

All that said, you can certainly do more interesting things with WinJS.log if you want. You could, for example, have the function call msWriteProfilerMark and use it more for perf checking than error logging (in which case you can filter on a type of "perf" or something like that).

With console.log, it's helpful to know that you can, if desired, save that output in the system Event Log, visible in Event Viewer. The steps to do that are as follows:

  1. Launch Event viewer (eventvwr.exe)
  2. Under Application And ServicesMicrosoftWindowsAppHost node, use the context menu to View->Show Analytic and Debug Logs
  3. Once the App Tracing channel shows up under the AppHost node, use the context menu to “Enable Log”
  4. Restart your app
  5. The console messages should now be in event viewer

You'll see a bunch of other events from wwahost.exe showing up here too, but you can filter on your process ID to whittle down the list. It's best to be running only your app when checking the Event Viewer!

Finally, if you use WinJS.log, you'll want to make sure it isn't being employed in release versions of your app. For this reason, when callign WinJS.log, use the same syntax as WinJS: WinJS.log && WinJS.log(…). This way you won't be spending extra cycles in your release version writing to a console that the user will never see.

Then be sure to remove the one line that assigns a function to WinJS.log (or calls WinJS.Utilities.startLog) before you build your package to upload to the Store. This is much easier than trying to scrub your app for direct console.log calls.

Thanks to Josh Williams and Andy Sterland who provided many of the details here.

In Part 1 we looked at basic class definitions using WinJS.Class and how this helper gives you a structure through which you can define classes without directly messing with object prototypes.

In this part we’ll look at the next piece in WinJS.Class, namely WinJS.Class.derive. As you’d expect, this method allows you to basically add instance and static members to an existing class. The syntax is:

WinJS.Class.derive(baseClass, constructor, instanceMembers, staticMembers);

where baseClass is the name of a class previously defined with WinJS.Class.define or WinJS.Class.derive, or, for that matter, really any other object. The other three parameters are the same as those of WinJS.Class.define, with the same meaning.

Peeking into the WinJS sources (base.js), we can see how derive works:

if (baseClass) {
    constructor = constructor || function () { };
    var basePrototype = baseClass.prototype;
constructor.prototype = Object.create(basePrototype);

    Object.defineProperty(constructor.prototype, “constructor”, { value: constructor, writable: true, configurable: true, enumerable: true });

    if (instanceMembers) {
        initializeProperties(constructor.prototype, instanceMembers);

    if (staticMembers) {
        initializeProperties(constructor, staticMembers);

    return constructor;
} else {
    return define(constructor, instanceMembers, staticMembers);

You can see that if baseClass is null, derive is just an alias for define, and if you indicate null for the constructor, an empty function is provided. Otherwise you can see that the derived class is given a copy of the base class’ prototype, so that the two won’t interfere with each other. After that, derive then adds the static and instance properties as did define.

Because baseClass already has its own instance and static members, they’re already present in its prototype, so those members carry over into the derived class, as you’d expect. But again, if you make later changes to members of that original baseClass, those changes only affect the derivation and not the original.

Looking around the rest of WinJS, you’ll see that derive is used in a variety of places to centralize implementation that’s shared between similar controls and data sources, for example.

To handle otherwise unhandled exceptions at the application level, you can use the window.onerror event or the WinJS.Application.onerror event.

The key difference between the two is that WinJS.Application.onerror handles only exceptions that occur within WinJS’s own event dispatching mechanism. This includes any exceptions that happen within asynchronous operations, as those involve promises and promises employ that dispatching mechanism. So that handler will see exceptions that come out of WinRT and other parts of WinJS. It won’t see errors that arise from elsewhere, however, such as if you’re using XmlHttpRequest directly instead of WinJS.xhr, or you throw an exception somewhere else in your code. Those you can only capture in window.onerror.

If you have both handlers in place, WinJS.Application.onerror will see any unhandled WinJS/WinRT exceptions first. If you don’t handle them there, they’ll go onto window.onerror.

Either way, it’s a good idea to have such handler in place in your debug build, as you can then catch any unhandled exception before you get to the ominous chunk of code in WinJS (terminateAppHandler) that calles MSApp.terminateApp().


Much has been written in the community about object-oriented JavaScript, and various patterns have emerged to accomplish with JavaScript’s flexible nature the kinds of behaviors that are built directly into a language like C++. Having myself done plenty of C++ in the past, much more than true functional programming, I’ve found the object-oriented approach to be more familiar and comfortable.

One place OO programmers can hit a bump in JavaScript is the lack of a clear idea of a “class,” that is, the definition of a type of object that can be instantiated. JavaScript, in short, has not class keyword. Instead it has functions, and only functions. Conveniently, however, if you create a function that populates members of the this variable, the name of that function works exactly like the name of a class.

To borrow a snippet of code from Eloquent JavaScript (a book I like for its depth and brevity, and which is also available for free in electronic form, thank you Marijn), take following function named Rabbit:

function Rabbit(adjective) {
this.adjective = adjective;
this.speak = function (line) {
print(“The “, this.adjective, ” rabbit says ‘”, line, “‘”);

By itself, this function really doesn’t do anything meaningful. You can call it from wherever and this will end up being your global context. Maybe handy if you like to pollute the global namespace!

When used with the new operator, on the other hand, this type of function becomes an object constructor, and effectively defines a class as we know in OO programming. We can use it as follows:

var fuzzyBunny = new Rabbit(“cutie”);
fuzzyBunny.speak(“nibble, nibble!”);

As Marijn points out, using new with a constructor function like this has a nice side effect which is to assign the object’s constructor property with the constructor function itself. This is not true if you just create a function that returns a newly instantiated object.

To make our class even more object-oriented, the other thing that we typically do is assign default values to properties and assign methods within the class, rather than on individual instances. In the first example above, each instance gets a new copy of the anonymous function assigned to speak. It would be better to define that function such that a single copy is used by the different instances of the class. This is accomplished by assigning the function to the class’ prototype as so:

function Rabbit(adjective) {
this.adjective = adjective;

Rabbit.prototype.speak = function (line) {
print(“The “, this.adjective, ” rabbit says ‘”, line, “‘”);

Of course, having to write this syntax out for each and every member of the class that’s shared between instances is both cumbersome and prone to errors. Personally, I also like to avoid messing with prototype as you can really hurt yourself if you’re not careful.

Thus WinJS provides a helper that provides a cleaner syntax as well as clear separation between the constructor function, instance members, and static members: WinJS.Class.define:

var ClassName = WinJS.Class.define(constructor, instanceMembers, staticMembers);

where constructor is a function and instanceMembers and staticMembers are both objects. The general structure you see in code looks like this (you can find many examples in the WinJS source code itself):

var ClassName = WinJS.Class.define(
function ClassName_ctor() { //adding _ctor is conventional
//Instance members
//Static members

As many classes don’t have static members, the third parameter is often omitted. Also, if you pass null as the constructor, WinJS will substitute an empty function in its place. You can see this in the WinJS source code for define (base.js, comments added):

function define(constructor, instanceMembers, staticMembers) {
constructor = constructor || function () { };

    //Adds a supportedForProcessing property set to true. This is needed by
//WinJS.UI.process[All], WinJS.Binding.process, and WinJS.Resources.process.

    if (instanceMembers) {
initializeProperties(constructor.prototype, instanceMembers);

    if (staticMembers) {
initializeProperties(constructor, staticMembers);

    return constructor;

You can also see how define treats static and instance members (initializeProperties is a helper that basically iterates the object in the second parameter and copies its members to the object in the first). Static members are specifically added as properties to the class function itself, constructor. This means they exist singularly on that object—if you change them anywhere, those changes apply to all instance. I consider that a rather dangerous practice, so I like to consider static members as read-only.

Instance members, on the other hand, are specifically added to constructor.prototype, so they are defined just once (especially in the case of methods) while still giving each individual instance a copy of the properties that can be changed without affecting other instances.

You can see, then, that WinJS.Class.define is really just a helper: you can accomplish everything it does with straight JavaScript, but you end up with code that’s generally harder to maintain. Indeed, the team that wrote WinJS really needed these structures for themselves to avoid making lots of small mistakes. But otherwise there is nothing magical about WinJS.Class.define, and you can use it in your own app code or not.

Along these lines, people have asked how WinJS.Class.define relate to the class structures of TypeScript. When all is said and done, they accomplish the same things. In fact, you can derive WinJS classes from TypeScript classes and vice-versa.

The one exception is that call to WinJS.Utilities.markSupportedForProcessing in WinJS. This is a requirement for functions that are used from other parts of WinJS (see Chapter 4 of my book, pages 145-146) and is the only “hidden” benefit. If you use TypeScript or other libraries to create classes, you’ll need to call that function directly.

In Part 2 of this topic, we’ll look at WinJS.Class.derive. In Part 3 we’ll finish up with WinJS.Class.mix and the idea of mixins.

HTML5 includes facilities for client-side “web storage” from within JavaScript as a great improvement over cookies. For reference, see for an overview, for the spec. In Windows Store apps written in HTML/CSS/JavaScript, these features overlap with the application storage APIs in WinRT. In this article I’ll compare and contrast the two.

Note: one key difference for any comparison with WinRT APIs is that HTML and native JavaScript APIs are available in the web context whereas WinRT is not. This comparison therefore only applies to pages running in the local context. In the web context you must use the HTML5/JS APIs.

It’s also helpful to note that overlaps such as these exist (a) because of the local and web contexts, and (b) to provide the capability to Windows Store apps written in other languages where an intrinsic API is not available.


In Web Storage, there is local and session storage that differ in scope and lifetime. Local storage is per-domain and persists after the browser is closed. Session storage is per-page/per-window and is cleaned up when the window is closed. If you have multiple windows open with the same site, the benefit here is that session storage is kept separate.

The storage itself is an associative array of strings at present; there is a proposal spec for structured data.

Two such associative arrays are made available in JavaScript: localStorage and sessionStorage. You can create any property in them you want, and retrieve them as you want (checking for existence first, of course):

if ( { … }

if (!localStorage.pageLoadCount)
localStorage.pageLoadCount = 0;

localStorage.pageLoadCount += 1;
document.getElementById(‘count’).textContent = localStorage.pageLoadCount;

The WinRT APIs are available through the Windows.Storage.ApplicationData class, which gives you access to StorageFolder objects for Local, Temp, and Roaming areas of AppData along with localSettings and roamingSettings (containers for key-value pairs including sub-containers). The Application object in the Windows Library for JavaScript (WinJS) also contains a local, temp, and roaming objectsto simplify working with the ApplicationData APIs (it also has a sessionState object into which you can write values, but these are only restored if an app is restarted after being terminated by Windows when freeing up memory). For details, see Chapter 8 of my book (as well as sections of Chapter 3).

Comparing the APIs:

  • HTML5 sessionStorage (per window) in browsers is effectively the same as local variables in an app, because typically you use a single-page navigation model (with DOM replacement) to preserve the script context across pages. From an app’s point of view, then, In other words, sessionStorage is just a global array that had an automatic new done for it. That’s all.
  • WinRT local and HTML5 web local storage both use persistent storage that is available to the app across instances, that is, if the app runs and writes to local storage, is then closed by the user, then restarted, the local storage values are persistent.
  • HTML5 web storage has only a simple array model with strings. WinRT is much richer, with type-specific settings, hierarchical containers, composite settings (groups of settings that act as a single unit), and also supports unstructured (binary) data in arbitrary files. You’d have to encode binary data into text for web storage.
  • Web storage works on a synchronous model; WinRT is synchronous for settings, asynchronous for files.
  • WinRT and HTML5 storage are both kept in the user’s AppDatapackages<package> folder and is automatically cleaned up when the app is uninstalled.
  • WinRT supports automatic roaming through the RoamingSettings container and Roaming folder (up to 100K total data); HTML5 web storage is entirely local.
  • WinRT supports a temp folder that can be cleaned out with the Disk Cleanup tool. This makes a great place for caching data that can be restored at another time.


For small bits of data, an app might use HTML storage for the sake of simplicity if you’re familiar with the API. However, it means having a different (and UI-thread blocking) programming model from the roaming settings and a lack of unstructured data (file) capability. One also has to watch out for the fact that all the data are a strings and will be handled like strings. So for the code that does the launch count as above (which is pulled from the W3C spec), when you reload the pageLoadCount at a later time, the data type is actually a string, and adding 1 doesn’t increment the value, it appends “1” to the string. You have to do a parseInt on the value from localStorage to get a numerical value again.

The other comparison to make between these methods is to review the storage limits imposed by each mechanism, as summarized in the following table. For completeness, we’ve also included other storage HTML5 mechanisms like IndexedDB and AppCache as these also employ the app’s AppData area on the file system.

Storage Method Limit (up to file system capacity)
Web storage (local) 10MB
Web storage (session) 10MB
WinRT localSettings
(structured settings)
  • 8K per individual setting (1)
  • 64K per composite setting (1)
  • No limit on overall settings
WinRT localFolder
(unstructured files)
WinRT roamingSettings
(structured settings)
  • 8K per individual setting (1)
  • 64K per composite setting (1)
  • No limit on overall settings. Exception:   sync engine may limit total amount of roamingSettings and roamingFolder   data that will roam (2)
WinRT roamingFolder
(unstructured files)
No storage limit. However, the sync engine limits total the   amount of roamingSettings and roamingFolder data that will   actually roam. (2)
WinRT tempFolder
(unstructured files)
None (3)
Cookies 4K per cookie; no limit on total cookies
History None
Temporary Internet Files None (4)
IndexedDB 250MB per app, 12.5% of overall storage or 1TB, whichever is   less.
HTML5 Appcache None (4)


(1)    These are arbitrary limits and may change.

(2)    The default sync engine presently imposes a 100K limit (see the roamingStorageQuota property); if the combined contents of the roamingSettings and roamingFolder exceed that limit, the settings will still only be stored locally and no data is roamed. Again, this is a limit of the sync engine: the WinRT APIs themselves don’t impose limits. Different sync engines can behave differently.

(3)    Files created in the tempFolder are subject to deletion by Windows’ Disk Cleanup utility.

(4)    Current design with Windows Store apps does not impose a storage limit for AppCache (along with any other cached files from the web); IE will continue to enforce user- and system-defined limits.


In the end, if you’re writing new code, I recommend using the WinRT APIs to have a consistent async programming model across local, roaming, and temp data. If you have existing code that uses HTML5 web storage, it will continue to work subject to the limits outlined above.

A few week ago I answered a question on the MSDN forums that basically asked, “I ran code in a promise, so why didn’t it run asynchronously.” It was a good opportunity to clarify the nature of a promise and the relationship between promises and asynchronous code. So here I offer an edited version of my response.

The basic thing to understand is that a promise is just a way of saying “execute this code when the promised value becomes available (that is, when the promise of that value is fulfilled).” It says nothing about how the code is actually run in the CPU scheduler. So if you take a block of code and just wrap it with or such, e.g.:

return new WinJS.Promise(function (complete) {  /* some code */ });

you’re just saying that /* some code */ will execute when you call the promise’s then/done methods, but all that still happens on the UI thread.

True async behavior–that is, running code on another thread–happens through three means:

  1. A JavaScript worker (web worker), which you can wrap in a promise (new WinJS.Promise to handle the worker messages) in order to chain/join the async operation to others.
  2. An async method written in a C#/VB WinRT component where the code uses the Task class.
  3. An async method written in a C++ WinRT component where the code uses the concurrency library.

In the latter two cases, async methods (including those from the built-in WinRT APIs) happen to be projected into JavaScript as promises; in #1 you use new WinJS.Promise to do the same manually. But in every case, it’s not the promise that runs code on another thread–it’s purpose is just to manage completed/error/progress handlers. It’s the underlying worker or async method that runs code on another thread.

Creating async APIs in WinRT components as well as with web workers is something I cover in Chapter 16 of my book, in the section “Implementing Async Methods,” if you want all the details.

Here’s a link to the original forum discussion where I extract some of those details.