Firing DOM events is the most common way for JavaScript/HTML components to send notifications to each other. If you are building a Windows Store app with JavaScript, you’ll likely need to mix asynchronous calls to Windows APIs with other logic that is waiting on DOM events. This can get messy and repetitive if you try to manage DOM event listeners manually. But waiting for a DOM event is asynchronous anyway, so we can wrap it in a promise.
Wrapping it in a promise abstracts away the calls to addEventListener and removeEventListener, and allows us to compose this type of action with other promises. For example, let’s assume we want to insert an <img> element and then wait for it to load. Loading an image can take on the order of seconds depending on the size and location, so waiting for the load needs to be an asynchronous action or it will hang your app.
An HTML <img> will either load successfully and fire the load event, or it might fail to load and fire the error event. We only need to wait for one of these events to fire, so we can use WinJS.Promise.any() and our waitForSingleEventAsync() function above to create a promise that will either be fulfilled with the loaded image element or it will fail with the error “Image load failed”. Additionally, if the image load is already complete, we just return immediately.