有我认为应该是一个相对容易处理的问题是一个主要的痛苦......我正在努力做:
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/