Sammy Ageil

Disambiguation of Technologies

Create an Asynchronous findControl function in WinRT javascript

In our last tutorial we created a findControl function and used it to return a valid winRT's winControl.
Today we will add the Asynchronous version of our method. Asynchronous operations in javascript's WinRT are handled using javascript's Promises or deferreds patterns.
So what is a promise pattern?
A promise or deffered is an object which represents the output of some computation which hasn't necessarily happened or completed yet. When you try to use the value in a promise, the program waits for the computation to complete then returns the computed value to the caller. It is critical to understand that Promises DO NOT create new threads.Promises simply provide a convenient way to do something when something else is done.

Now we understand what is a promise pattern, let's see our Asynchronous findControl and use it;

/// <reference path="//Microsoft.WinJS.1.0/js/base.js" />
/// <reference path="//Microsoft.WinJS.1.0/js/ui.js" />
"use strict";
WinJS.Namespace.define("MyApplication.Utils", {
    findControl: function (ctrlId) {
        return document.getElementById(ctrlId).winControl;
    findControlAsync: function (ctrlId) {
        return new WinJS.Promise(function (completed, error) {
            var ctrl = document.getElementById(ctrlId);
            if (ctrl !== undefined && ctrl !== null) {
            else {

This script is the exact script from our previous tutorial. The only addition here is the new function declared as findControlAsync. This function uses WinJS.Promise to create our findControlAsync; to call our function we use the following script:

MyApplication.Utils.findControlAsync("lView").then(function (ctrol) {
    //write to console findControlAsync result is true when the control is found
    console.log("findControlAsync result is = ", ctrol !== null && ctrol !== undefined);
}, function () { console.error("The specified control was not found in the DOM") });

Note "the lView string parameter is the control id for a winJS listView that I have in my default html page"

So what does our call exactly mean?, this call simply calls the findControlAsync, if the call succeeds, we use the control to print the specified message otherwise we print a message indicating "the specified control was not found in the DOM".

Comments (1) -

  • Mike

    3/19/2013 7:00:53 PM |

    Very cool.

Pingbacks and trackbacks (1)+

Comments are closed