您的doSomething() 函数不返回任何内容,这意味着使用它的赋值将是undefined。但是,这并不是真正的问题。
根本问题是您似乎在这里混合了两种不同的数据处理模式:如果您正在编写纯同步代码,则使用返回函数(立即返回一些值)。如果您需要异步代码,请使用回调(这将“最终”执行某些操作)。混合这两种模式会导致问题和挫败感:
要么:
- 不要将您的函数命名为“回调”,并让它返回其处理后的值,或者
- 让回调负责执行您要对
val 执行的任何操作。
案例一:
function doSomething(data, processor) {
return processor(data);
}
function passThrough(v) { return v; }
var val = doSomething("test", passThrough);
// immediately use "val" here in for whatever thing you need to do.
案例 2:
function doSomething(data, callback) {
// _eventually_ a callback happens - for instance, this
// function pulls some data from a database, which is one
// of those inherently asynchronous tasks. Let's fake that
// with a timeout for demonstration purposes:
setTimemout(() => callback(data), 500);
}
function handleData(val) {
// use "val" here in for whatever thing you need to do. Eventually.
}
doSomething("test", handleData);
如果你想使用案例 2,你真的想看看现代 Javascript 中的“Promises”和 async/await,它们是基于“一旦有事情就回调的想法”的高度改进的方法回电”。
2021 年编辑:自最初编写此答案以来的第三个选项是使用 async/await 模式,它是 Promises 周围的语法糖。
案例 3:
async function doSomething(input) {
// we're still _eventually_ returning something,
// but we're now exploiting `async` to wrap a promise,
// which lets us write normal-looking code, even if what
// we're really doing is returning a Promise object,
// with the "await" keyword auto-unpacking that for us.
return someModernAsyncAPI.getThing(input);
}
function handleData(val) {
// ...
}
async function run() {
const data = await doSomething("test");
handleData(data);
}
run();