JS continue after multiple .load()-functions done

I’m having a problem with an asynchronous JS function. Well I have a function which inserts elements one by one. This works. But I would like to continue after all .load()-functions are done.

The way I’ve implemented the Deferred() part is obviously wrong but I have no clue how to achieve this.

Note: I have simplified the code for a better clarity.

var d = new jQuery.Deferred();
var i = index;
function loadView() {
    if(i > -1 && i < array.length) {
        if(!jQuery.contains(document.documentElement, $(selector)[0])) {
            /* do stuff here */
            panel.load(myPHPfile, function() {
                $dom.append($(selector));
                i++;
                if(i < array.length) {
                    loadView();
                    d.resolve();
                }
            });
        }
    }
}
loadView();

jQuery.when(d).then(function() {
    /* when all elements are insert, do something */
});

I am thankful for any help!


Source: stackoverflow-javascript

One button submits AJAX, another button queries result of that AJAX

This question is part of me trying to learn promises and deferreds. Suppose you have a button that submits a POST:

$("#submit").click( function() {
  $.post({...})
})

My understanding is that AJAX is itself a promise (which makes obvious sense), so what I’d like to do is, when user clicks #check, it returns the output of the AJAX once it is complete (assuming that #check can and will always be clicked only after #submit has been clicked).

I thought this was simple enough, so my initial code was:

$("#check").click(function() {
  $.when($.post({...})).done( function(data) {
    console.log("data")
  })  
})

But I realize that in this implementation, the AJAX wouldn’t start POSTing until #check is clicked. There’s no need for any #submit button and having the AJAX .post in #submit is redundant.

Is there a way to achieve what I’m doing using promises/deferreds?


Source: stackoverflow-javascript