我应该使用“返回"吗?用我的 Javascript 回调函数? [英] Should I use ''return" with my callback function in Javascript?

查看:26
本文介绍了我应该使用“返回"吗?用我的 Javascript 回调函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 JS 应用程序中使用异步函数,其中包含我自己的接收回调输入的函数.当我调用回调函数时,是否需要使用return"关键字?有关系吗?有什么区别?

I am using asynchronous functions in my JS application wrapped with my own functions that receive callback inputs. When i call the callback function, do I need to use the "return" keyword? does it matter? whats the difference?

例如:

var getData = function(callback){
    // do some aysnc db stuff...
    return callback(results);
    // or just
    callback(results);
}

PS:我正在使用 javascript 编写一个混合移动应用程序.

PS: I am writing a hybrid mobile appiliction using javascript.

推荐答案

如果您的函数中只有一条路径,那么您几乎可以互换使用这两种形式.当然,如果没有返回,函数的返回值将是未定义的,但是您的调用代码可能无论如何都没有使用它.

If you only have one path through your function then you can use both forms pretty much interchangeably. Of course, the return value from the function will be undefined without the return, but your calling code is probably not using it anyway.

确实如此

return callback()

实际上等同于

callback(result); return;

后者确实会在调用堆栈上产生一个额外的帧,因此会使用更多的资源.我想如果你有很多嵌套的回调,或者正在做递归,你会更快地耗尽堆栈空间.

The latter does result in an additional frame on the call stack, and so uses more resources. I suppose if you had many nested callbacks, or were doing recursion, you'd run out of stack space more quickly.

这可能是个坏主意,我不认为我是在说回调之前的返回更惯用.

It's probably a bad idea and I don't think I'm sticking my neck out in saying that the return before the callback is way more idiomatic.

当您的函数中有多个路径时,您必须小心.例如,这将按您的预期工作:

When you have multiple paths in your function, you have to be careful. For example, this will work as you expect:

(cb)=> {
    if (something) cb('a')
    else cb('b')
}

然而,在这种情况下,两个回调都会被调用.

However, in this case, both callbacks will be called.

(cb)=> {
    if (something) cb('a');

    cb('b')
}

当您阅读以上内容时,很明显两者都会被调用.然而,编写这样的代码是一个典型的节点新手错误(尤其是在处理错误时).如果您想要或被执行,您需要:

When you read the above, it's pretty clear that both will be called. Yet writing code like that is a classic node newbie mistake (especially when handling errors). If you want either or to be executed you need:

(cb)=> {
    if (something) return cb('a');

    cb('b')
}

这篇关于我应该使用“返回"吗?用我的 Javascript 回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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