1

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!

1 Answer 1

1

If i < array.length after incrementing, that means you're not done, so you don't want to resolve your Deferred there. Instead:

if(i < array.length) {
    loadView();
} else {                   // ***
    d.resolve();
}

Separately, you don't need to use jQuery.when. Just:

d.then(function() {
    /* when all elements are insert, do something */
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.