Please help me with multiple deferreds

Please help me with multiple deferreds

Hi,

Please go easy on me, I'm very new to Javascript and JQuery.

I'm doing some Javascript development for Microsoft CRM. My scenario is that I am adding contacts to an event (like a meeting). The screen shows a bunch of contacts which can be selected. Without going into too much CRM detail I am getting each selected contact and doing a service call to add it to the event, I'm using $.ajax to do this and adding the returned deferred for the add of each contact to an array.

Some of these calls may fail because the contact is already added, and of course they may fail for other reasons.

All I want to then do is display a message saying "5 contacts added, 3 already exists, 2 failed" or something along those lines.

I've been playing around with when/then/always to try and figure out how to do this. I think I've come to the conclusion that "always" is what I want as I believe this gets called regardless of the individual success and failure.

I'm really struggling to work out what exactly is getting passed to the always function, and how I can just get the set of results from all my service calls so I can work out which ones failed.

I've tried using the arguments array, but this seems to only populated for success, if only one fails I no longer seem to get an array so I can't work out which ones failed. Any help/hints would be greatly appreciated.

This is how my code currently looks (with stupid debug lines). the deferred object is actually my array of deferreds...

  1. // check if all ajax calls have finished
        $.when.apply($, deferred).always(function()
        {
            if ($.isArray(arguments))
            {
                window.console.log(arguments[0][2]);
            }
            else
            {

            }


            window.console.log(arguments[0][2]);
            window.console.log("All finished");
            alert("Finished adding your chosen contact(s) to the event.");
        });