我应该使用''回归"在JavaScript中我的回调函数? [英] Should I use ''return" with my callback function in Javascript?

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

问题描述

我正在使用包裹接收回调投入我自己的功能我JS应用异步函数。当我调用回调函数,我需要用回归的关键字?有关系吗?什么区别呢?

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写一个混合移动appiliction

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

推荐答案

如果你只有一个路径通过你的功能,那么你可以使用这两种形式的pretty多少互换。当然,从函数的返回值将不返回是不确定的,但你的code可能没有使用也无妨。

If you only have one path through you 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;

但我会坚持我的脖子出来,说,前者是更地道。

but I'll stick my neck out and say that the former is 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')
}

当你看了上面的,它是pretty明确表示,两者都将被调用。然而,写code喜欢就是(尤其是在处理错误时)的经典节点新手的错误。如果你想或来执行你需要:

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天全站免登陆