TechBubbles Microsoft Technology BLOG

Using Promises in JavaScript

Promises in JavaScript gives you great power of asynchronicity while you are creating Windows 8 Apps or Web Applications. Promises gives you the ability to call something without blocking your UI thread. Instead of waiting for a call to return something, let that function fire when it complete. In this way you can continue the execution for the user. You are definitely need to know and use promises if you are going to develop Windows Apps. The reason is in Windows RT which is the API on windows where you develop the Apps. If a function might take more than 50 milliseconds then that is an asynchronous function. Windows team developed those functions as Asynchronous function, in order to use these functions you need to call them Asynchronously.

Concept

When you call an asynchronous function, you get the promise back and promise is an object. Promises are not exclusively a windows thing, they are JavaScript thing. The below examples explains the Promises Concept

function longTaskSync() {
        var start = new Date().getTime();
        var delay = SECONDS_DELAY * 1000;
        while (new Date().getTime() < start + delay);
    }

The above function has a while loop which has a “x” number of seconds delay and blocks the UI thread. You can not do anything until you get to the end of it. This is not an acceptable user experience.

function longTaskAsync() {
        var seconds = 0;
        var intervalId = window.setInterval(function () {
            seconds++;
            if (seconds >= SECONDS_DELAY) {
                window.clearInterval(intervalId);
            }
        }, 1000);
    }

The above code does not block your UI but the task actually did not finish.

Now use the promise with async task without blocking the UI and do anything until that task is complete.

function longTaskAsyncPromise() {
        return new WinJS.Promise(function (c, e, p) {
            var seconds = 0;
            var intervalId = window.setInterval(function () {
                seconds++;
                p(seconds);
                if (seconds >= SECONDS_DELAY) {
                    window.clearInterval(intervalId);
                    c();
                }
            }, 1000);
        });

when you use this promise pattern then you will know what happens and when.

Consuming a Promise

var method1 = q(".promises #uses .method1");
        q("button.start", method1).onclick = function (e) {
            longTaskAsyncPromise().then(function () {
                q("progress", method1).value = 100;
            });
        };
        q("button.reset", method1).onclick = function (e) {
            q("progress", method1).value = 0;
        };

first line in above code contains everything regarding the method1 then use that q function to define the button and when the button is clicked then you are defining a function to run. LongTaskAsync returns a promise and it has a then method in the example passes a function and tells you want to see that result whenever that promise is complete.

Creating a Promise

var method3 = q(".promises #uses .method3");
        q("button.start", method3).onclick = function (e) {
            function myAsyncFunction() {
                return new WinJS.Promise(function (c, e, p) {
                    //do something that might take longer than 50ms
                    try {
                        longTaskAsyncPromise().then(function () {
                            c();
                        });
                    }
                    catch (err) {
                        e(err);
                    }
                });
            }

            myAsyncFunction().then(function () {
                q("progress", method3).value = 100;
            });
        };

To create a promise you have to call new WinJS promise, this new WinJS promise in above code expecting you to pass a function and that function needs to have three parameters ‘c’ stands for complete , ‘e’ stands for error message and ‘p’ stands for progress. Inside the context of function you can call c, p and e functions. You have the control over promise to complete.

About the author

Kalyan Bandarupalli

My name is kalyan, I am a software architect and builds the applications using Microsoft .NET technologies. Here I am trying to share what I feel and what I think with whoever comes along wandering to Internet home of mine.I hope that this page and its contents will speak for me and that is the reason I am not going to say anything specially about my self here.

1 Comment

  • “Promises are not exclusively a windows thing, they are JavaScript thing.” …
    Is their a way to create promise without using windows library “WinJS” ?

TechBubbles Microsoft Technology BLOG

Follow me

Archives

Tag Cloud