How to handle nested jquery deferred calls

本秂侑毒 提交于 2019-12-07 05:36:18

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/17095023/how-to-handle-nested-jquery-deferred-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!