Javascript:使用return调用回调有什么不同?

Javascript:使用return调用回调有什么不同?,javascript,callback,return,Javascript,Callback,Return,想象一下这样的代码: function foo(data) { // ... do something with data } function do(userInput, callback) { callback(userInput); } function doWithReturn(userInput, callback) { return callback(userInput); } // ... do('Hello, World', foo); doWith

想象一下这样的代码:

function foo(data) {
    // ... do something with data
}

function do(userInput, callback) {
    callback(userInput);
}

function doWithReturn(userInput, callback) {
    return callback(userInput);
}

// ...
do('Hello, World', foo);
doWithReturn('Hello, World', foo);
使用纯do()而不是doWithReturn()有什么好处吗


我这样问是因为,假设我们不知道foo()在内部做了什么(例如,可能它有一个return语句,可能它只是触发了一个dumb
alert(data)
),使用doWithReturn调用foo()似乎总是“更安全”,因为如果foo()恰好返回一个值,不使用doWithReturn显然是错误的。

如果函数返回一个值,这表明它可能有用。我会为函数选择一个名称,一旦出现某个返回值有益的场景,我会添加一个返回值


我不知道这是否回答了您的问题。

完全取决于您正在编写的函数的性质。当您的
do/doWithReturn
函数变得更像真实世界的应用程序时,如果返回值应该传递,通常会变得更清晰。使用函数而不知道其内部如何工作是可以的,但我不会在不知道其返回内容的情况下使用函数。。。