Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle nested jquery deferred calls

I have a function to get some data, and the function should return a promise. In the function, I have to made 2 requests - one after another. I ended up with a nested deferrer call where the last call resolves on the deferrer the function will return. I'm new to this deferred stuff and wonder if this is the right solution.

function getData(func) {
    var model = new Model();
    var collection = new Collection();
    var dfd = new jQuery.Deferred();

    collection.fetch().then(function () {
        model.fetch().then(function () {
            dfd.resolve(collection);
        });
    });

    return dfd.then(function (collection) {
        return getViews(func(collection), model);
    });
}
like image 307
Andreas Köberle Avatar asked Jun 13 '13 19:06

Andreas Köberle


2 Answers

Andreas, I see you have quite correctly accepted Vitaliy's answer and I'm not trying to steal his points but just in case you are not aware, there's no need to create and resolve your own $.Deferred() and there's no need to pass collection around (except to func()) as it remains in scope.

As far as I can tell from the code in the question, the following should work :

function getData(func) {
    var collection = new Collection();
    var model = new Model();
    return $.when(collection.fetch(), model.fetch()).then(function() {
        return getViews(func(collection), model);
    });
}
like image 116
Beetroot-Beetroot Avatar answered Nov 10 '22 15:11

Beetroot-Beetroot


If the order of the calls does not matter I would suggest to use http://api.jquery.com/jQuery.when

With when you can make parallel xhr requests.

like image 26
Vitalii Petrychuk Avatar answered Nov 10 '22 14:11

Vitalii Petrychuk