jQuery.Deferred in recursive cycle

jQuery.Deferred in recursive cycle

本文关键字:cycle recursive in Deferred jQuery      更新时间:2023-09-26

我的代码中有一个复杂的异步函数问题。我有一个对象,我必须对其应用不同的功能(动画、内容分析等)。

this.buildChain = function (data, func, func_at, func_after) {
            //first I launch some function              
            func.apply(animData, arguments);
            //then I filter an array of objects             
            data.filter(function(e){
                if(e.trigger == 'at' && e.link == animData.id) return true; 
            }).forEach(function(e){
                //And apply the function to all objects that've been filtered
                //These  functions apply at the same time as the first, "func"                  
                func_at.apply(e, arguments);
            });
            //When my "func" and all "func_at" operations are resolved, I have
            //to filter my array again and execute "func_after" function
            data.filter(function(e){
                if(e.trigger == 'auto' && e.link == animData.id)  return true;
            }).forEach(function(e){
                func_after.apply(e, arguments);
            });
        };

问题是,我必须将此buildChain函数应用于递归函数:

function playChain(animData){
            function func() {
                //some action
            }
            function func_at () {
                playChain(this);
            }
            function func_after () {
                playChain(this);
            }
            s.buildChain(data, animData, func, func_at, func_after);
        }

我知道,以某种方式可以用jQuery.Deffered()对象来解决,但是当涉及到递归循环时,我陷入了困境。因为实际的链可以从一个对象开始,所以很少有func_at,然后是一个func_after,然后又是一个func_at

我已经将返回解析$.Deferred()对象添加到我的函数中。

function playChain(animData){
            function func() {
                //some action
                return new $.Deferred().resolve();
            }
            function func_at () {
                playChain(this);
            }
            function func_after () {
                playChain(this);
            }
            s.buildChain(data, animData, func, func_at, func_after);
        }

然后我更正了构建链函数。

this.buildChain = function (data, animData, func, func_at, func_after) {
            function act1 () {
                var d = func.apply(animData, arguments);
                data.filter(function(e){
                    if(e.trigger == 'at' && e.link == animData.id) return true;
                }).forEach(function(e){
                    func_at.apply(e, arguments);
                });
                return d;
            }
            function act2() {
                data.filter(function(e){
                    if(e.trigger == 'auto' && e.link == animData.id)  return true;
                }).forEach(function(e){
                    func_after.apply(e, arguments);
                });
            }
            act1().done(act2);
        };