2012-12-03 93 views
3

有什么,我认为应该是一个比较简单的问题来处理是一个重大的痛苦......我试图做的事:的JavaScript嵌套函数内调用外部函数

a.b("param", function(data) 
{ 
    logger.debug("a.b(" + data.toString() + ")"); 

    if (data.err == 0) 
    { 
      // No error, do stuff with data 
    } 
    else 
    { 
      // Error :( Redo the entire thing. 
    } 
}); 

我的这种方法是尝试:

var theWholeThing = function() {return a.b("param", function(data) 
{ 
    logger.debug("a.b(" + data.toString() + ")"); 

    if (data.err == 0) 
    { 
      // No error, do stuff with data 
    } 
    else 
    { 
      // Error :( Redo the entire thing. 
      theWholeThing(); 
    } 
})}; 

上述的问题是,而前者没有工作(除了didnt交易时发生错误),后者根本不会打印日志信息......它犹如“theWholeThing()”呼叫没有像我想的那样工作(再次调用整个事物)。

这里一定有些微妙的错误,任何提示?

谢谢!

+1

递归罢工再次 –

回答

4

首先,直接回答你的问题,听起来好像你第一次忘记实际调用函数。尝试:

var theWholeThing = function() {return a.b("param", function(data) 
{ 
    logger.debug("a.b(" + data.toString() + ")"); 

    if (data.err == 0) 
    { 
      // No error, do stuff with data 
    } 
    else 
    { 
      // Error :( Redo the entire thing. 
      theWholeThing(); 
    } 
})}; 

theWholeThing(); // <--- Get it started. 

然而,这可以在一个名为IIFE(立即调用函数表达式)来实现多一点优雅:

// We wrap it in parentheses to make it a function expression rather than 
// a function declaration. 
(function theWholeThing() { 
    a.b("param", function(data) 
    { 
     logger.debug("a.b(" + data.toString() + ")"); 

     if (data.err == 0) 
     { 
       // No error, do stuff with data 
     } 
     else 
     { 
       // Error :( Redo the entire thing. 
       theWholeThing(); 
     } 
    }); 
})(); // <--- Invoke this function immediately. 
+0

这解决了这个问题,谢谢! (没有意识到问题是我没有调用函数开始...大声笑)将尽快接受答案所以让我(1分钟) –

0

如果你单独分开的方法和使用变量来表示,事情变得清晰。你只需要把你的a.b和匿名函数当作方法引用。我觉得这个代码示例可以帮助:

var theWholeThing = a.b, //this is a reference of b method 
    par = "param", 
    callback = function(data){ 
    logger.debug("a.b(" + data.toString() + ")"); 

    if (data.err == 0) 
    { 
      console.log("no error");  
    } 
    else 
    { 
      console.log("Error"); 
      // theWholeThing reference can be accessed here and you can pass your parameters along with the callback function using variable name 
      theWholeThing("param", callback); 
    } 
}; //declare the callback function and store it in a variable 

theWholeThing("param", callback); //invoke it