Search code examples
windows-8winjs

WinJS check xhr request is cancelled or not


I have few xhr requests as follows,

var promise=[];
promise[0]=.WinJS.xhr({
        type: "POST",
        url: "some url",
        data: somedata,
        headers: { "Content-type": "application/json; charset=utf-8" },
        //  responseType: "json"
    }).then(function(success){}, function(error){});

promise[1]=.WinJS.xhr({
        type: "POST",
        url: "some url",
        data: somedata,
        headers: { "Content-type": "application/json; charset=utf-8" },
        //  responseType: "json"
    }).then(function(success){}, function(error){});
promise[2]=...
.
.
.

Now i will cancel few requests for e.g promise[0], promise[5],

promise[0].cancel();
promise[5].cancel();

Now on join I want to know which all requests are cancelled,

WinJS.Promise.join(promise).done(function(xhr){
//here i should be able to check which requests are cancelled
});

Solution

  • The promise object has a second parameter where you can pass a function that will fire onCalcel.

    var aPromise = new WinJS.Promise(init, onCancel);
    

    The WinJS.xhr function work though in a sligtly different way.

    The error function is called when the operation is canceled, as well as for any errors that may occur during the download operation.

    xhrPromise = WinJS.xhr({ url: "<your choice of URL>" })
        .then(function complete(result) {
            //SUCCESS
        }, 
        function error(result) {
            if (result.name == "Canceled") {
                //CANCELED
            }
            else {
                //OTHER ERRORS
            } 
        });
    

    so if in the error function you return a specific value when it is "Cancel" then you will find this value once all the promises in the join are finished.