WinJS.Promise.Any – An example

Introduction:
WinJS.Promise.any gets invoked when any of a promise object finished its execution from a list of promise objects. We need to create an array of promise objects, which we are expecting to execute. On successful execution of any of the promise object from the array will invoke the “any” method to perform the tasks defined.

Scenario:
In this scenario, I need to execute a task on successful execution of a web services from a list of web services.

Solution:

HTML file content

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

JS 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.any(allPromises).then(function () {
                document.getElementById("mySpan").innerText = "At least one is 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.any waits until the array gets at least one of its values. After getting the value into it gets executed.

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