如何处理jQuery的嵌套调用推迟 [英] How to handle nested jquery deferred calls

查看:186
本文介绍了如何处理jQuery的嵌套调用推迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数来得到一些数据,函数返回一个承诺。在功能方面,我必须做2请求 - 此起彼伏。我结束了在deferrer函数将返回一个嵌套调用deferrer其中,最后调用议决。我是新来这个递延的东西,不知道这是正确的解决方案。

 函数的getData(FUNC){
    VAR模型=新模式();
    VAR收集=新的集合();
    VAR DFD =新jQuery.Deferred();    collection.fetch()。然后(函数(){
        model.fetch()。然后(函数(){
            dfd.resolve(集合);
        });
    });    返回dfd.then(功能(集合){
        返回getViews(FUNC(集合),模型);
    });
}


解决方案

安德烈亚斯,我看你已经非常正确接受了Vitaliy的回答,我不是要偷他的点,但以防万一你不知道,有没有必要创建和解决您自己的 $。递延(),而且也没有必要通过各地(除了 FUNC()),因为它仍然在范围内。

据我可以从问题的code告诉,下面应该工作:

 函数的getData(FUNC){
    VAR收集=新的集合();
    VAR模型=新模式();
    返回$。当(collection.fetch(),model.fetch())。然后(函数(){
        返回getViews(FUNC(集合),模型);
    });
}

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

解决方案

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

这篇关于如何处理jQuery的嵌套调用推迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆