WinJS.Promise – My Experiment to create some delay using loop

Intoduction:
WinJS.Promise is a class, which supports the asynchronous programming model. Upon the execution, program control executes the promise class and proceeds to the subsequent statement to execute. But it keeps track of the execution point to which control needs to get back after the promised function finished its execution.
A question was banging my head, whether I can create my own delay to the promise object and invoke Then/Done.

Description:
I tried 2 kind of exercises. But in both the exercise I had the HTML page common.

Exercise #1
Used the below code to create a delay by executing a long loop in an external method and returning a promise object from it. So that on completion, I can call Then method to do some task.

document.getElementById("mySpan").innerText = "Done";
MyProms(2).then(function (res) {
document.getElementById("mySpan").innerText = "then";
});
function MyProms(str) {
return new WinJS.Promise(function (comp, err, prog) {
for (var i = 0; i < 1000000; i++) {
document.getElementById("mySpan").innerText = i;
}
});
}

Expected result : Myspan value changed to “Done”. Some delay in execution and Myspan value changed to “Then”.

Actual result : Myspan value changed to “Done”. Some delay in execution and UI hanged till execution complete. Myspan value displayed as 999999.

Result : Fail

Reason : Although I am returning the promise object to the source, JavaScript is unable to create a separate thread. So it is executing in the main UI thread and hangs the UI.

Exercise #2
Used the below code to make a XHR call and get the response back. The content will get rendered on screen in a div.

WinJS.xhr({ url: "https://mindfiremobile.wordpress.com/ " }).done(
function (res) {
if (res) {
document.getElementById("mySpan").innerText = "Completed";
document.getElementById("myDiv").innerHTML = window.toStaticHTML(res.response);
}
});

Expected result : Normal execution. A delay in result population in div and mySpan value gets changed to “Completed”

Actual result : Same as expected

Result : Pass

Reason : WinJS handles this promises asynchronously. So they need not to be executed in the same UI thread.

Summary:
Lesson learned form the above experiment is, JavaScript cannot create a separate thread for execution by its own. In normal scenario, we can create a delay by calling the WinJS.Promise.timeout() method.

Written By: Nirmal Hota, Cross-Platform Mobile Lead, Mindfire Solutions

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s