0

I am trying to get $.when to work with my code. the case is that i have a method that fires alot of Ajax requests, and i want to show a loading screeen for the user while the requests rune. The when is so i can hide it after. Given what i have learned about $.when should the following code work, but the when function is never fired.

self.createTaggingDialog(self);
var ajaxArray = new Array();
self.containers.each(function () {
    var ImageClass = $(this).ImageTags();
    if (ImageClass != null) {
        ajaxArray.push(ImageClass.TagUser(ImageClass, username));
    }
});
$.when(ajaxArray, function () {
    console.log("DONE!");
    self.RemoveTagggingDialog(self);
});

Here is a value of the ajaxArray when it reaches the $.when enter image description here

The TagUser:

TagUser(self: ImageTags, username: string) {
    return $.ajax({
        type: "POST",
        url: self.options.UrlTagUser,
        data: {
            username: username,
            imageid: self.options.ImageId
        },
        success: function (data: UserAddJson) {
            if (data.Successful) {
                if (self.AddUserElement != null) {
                    self.AddUserElement.find('input').val('');
                    self.AddUserElement.modal('hide');
                }
                self.TagUserSuccess(self, data);
            } else {
                self.TagUserError(self, data.Message);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            self.TagUserError(self, "");
        }
    });
}
Androme
  • 2,399
  • 4
  • 43
  • 82
  • 1
    I assume `self.containers.each` is not asynchronous, then why do you need a `jQuery.when` that is typically used for deferreds? Just put your code from a callback below looping through a collection... – John Doe May 20 '13 at 09:52

1 Answers1

2

Try

$.when.apply($, ajaxArray).done(function () {
    console.log("DONE!");
    self.RemoveTagggingDialog(self);
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531