简体   繁体   English

如何处理嵌套的jquery延迟调用

[英]How to handle nested jquery deferred calls

I have a function to get some data, and the function should return a promise. 我有一个函数来获取一些数据,函数应该返回一个promise。 In the function, I have to made 2 requests - one after another. 在函数中,我必须一个接一个地提出2个请求。 I ended up with a nested deferrer call where the last call resolves on the deferrer the function will return. 我最终得到了一个嵌套的deferrer调用,其中最后一个调用在函数将返回的延迟器上resolves 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);
    });
}

If the order of the calls does not matter I would suggest to use http://api.jquery.com/jQuery.when 如果调用的顺序无关紧要,我建议使用http://api.jquery.com/jQuery.when

With when you can make parallel xhr requests. when你可以制作并行的xhr请求时。

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. 安德烈亚斯,我看到你已经非常正确地接受了维塔利的答案,我并不是想偷他的分数,但万一你不知道,没有必要创建和解决你自己的$.Deferred()并且没有必要通过collection周围(除了func() ),因为它仍然在范围内。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM