Javascript 从嵌套函数中调用外部函数

标签 javascript function function-calls nested-function

有我认为应该是一个相对容易处理的问题是一个主要的痛苦......我正在努力做:

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

上面的问题是前者确实有效(除了发生错误时没有处理),后者根本不打印日志消息……就好像“theWholeThing()”调用不起作用一样,因为我认为它应该(再次调用整个事情)。

这里一定有什么微妙的错误,有什么提示吗?

谢谢!

最佳答案

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

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.

关于Javascript 从嵌套函数中调用外部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13677678/

相关文章:

javascript - 纯动态页面——是否可行

javascript - 如何防止人们发送垃圾邮件 ajax 表单

r - 提取矩阵的对角线(不是非对角线)元素

c - 为什么函数调用没有被执行?

java - 如何通过 MySQL 触发器执行外部 java 函数?

c - 程序启动时间

javascript - 在 javascript 或 jquery 中的图像之间切换

javascript - 单击时显示 Gif,Ajax 成功后隐藏

c++ - 使用函数重载在 C++ 中调用具有整数的 char 等效函数

java - 函数调用与i+1,++i的实现有区别吗?