How to handle nested jquery deferred calls

2019-04-30 17:52发布

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);
    });
}

2条回答
Anthone
2楼-- · 2019-04-30 18:27

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.

查看更多
smile是对你的礼貌
3楼-- · 2019-04-30 18:35

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);
    });
}
查看更多
登录 后发表回答