0

I'm trying to get some data in multiple functions and would like to chain them in order to execute the last function only when all data was properly loaded.

The problem is that the functions in the .done() part will be called instantly and don't wait until the Deferred-Object is resolved. I also tried it by chaining them with .then() but this also didn't work.

var array1, array2;

function doStuffWithReceivedData() {
    // Working with the data
}

function getArray1() {
    var defArray1 = $.Deferred();

    $.getJSON(url, function(data) {
        if (data.success) {
            array1 = data.payload;
            defArray1.resolve();
        } else {
            // Information displayed that there was an error
        }
    })

    return defArray1;
}

// Function 2 is like the first one
function getArray2() {...};

$(document).read(function() {
    getArray1()
        .done(getArray2()
            .done(doStuffWithReceivedData()));
}
4
  • 2
    You're calling those methods, not giving their references. Remove the parenthesis. Commented Sep 5, 2017 at 9:55
  • use this-- getArray1().promise().done(function() { doStuffWithReceivedData() }); Commented Sep 5, 2017 at 9:56
  • stackoverflow.com/questions/15886272/… Commented Sep 5, 2017 at 9:56
  • 1
    Removing the parenthesis did the job! Thank you all. Commented Sep 5, 2017 at 9:59

1 Answer 1

1

The argument to .done() must be a function. You're calling the function, not passing it. Take off the parentheses.

$(document).ready(function() {
    getArray1()
        .done(function() {
            getArray2().done(doStuffWithReceivedData));
        }
}
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.