Using WinJS.Promise.Join-Executing a task after others finishes

Introduction:
WinJS.Promise.join is a method being exposed by the Promise object to deal with multiple promise objects execution.

Scenario:
This is a live scenario when I have received a task which will call a set of web services and perform certain action after the completion of all web services execution in an asynchronous mode.

Solution:
HTML file content

<body>
    <span id="mySpan"></span>
    <input type="button" id="btnCallPromise" value="Call my promise" />
    <span id="deSpan"></span>
</body>

HTML file content

(function () {
    "use strict";

    var mySites = new Array();
    mySites[0] = "https://mindfiremobile.wordpress.com/2013/12/27/start-stop-magic-in-winjs-application-object/";
    mySites[1] = "https://mindfiremobile.wordpress.com/2013/12/23/winjs-promise-my-experiment-to-create-some-delay-using-loop/";
    mySites[2] = "https://mindfiremobile.wordpress.com/2013/12/16/3d-effects-in-windows-store-app/";
    mySites[3] = "https://mindfiremobile.wordpress.com/2013/12/11/windows-store-app-flipview-custom-styling-part-3/";

    WinJS.Application.onready = function () {

        document.getElementById("btnCallPromise").addEventListener("click", function () {

            document.getElementById("deSpan").innerText = "";
            document.getElementById("mySpan").innerText = "";

            var allPromises = mySites.map(function (element) {
               return WinJS.xhr({ url: element }).then(function () {
                    document.getElementById("deSpan").innerText = document.getElementById("deSpan").innerText + "Completed : " + element.toString();
                });
            });

            WinJS.Promise.join(allPromises).then(function () {
                document.getElementById("mySpan").innerText = "We are all done";
            });
        });
    };

    WinJS.Application.start();
})();

Description :
In the above solution, I have declared an array, which contains the list of services that needs to be called. The mySites.map() method, which is used in the above program, gets the Promise object returned from the call and creates the allPromises array.

WinJS.Promise.join waits until the array gets all of its values. After getting all the values into it, executes the completed 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