如果我有以下代码:
var content;
var f = fs.readFile('./index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
return console.log(content);
});
f();
我得到以下信息:
f();
^
TypeError: undefined is not a function
如何返回一个未定义的函数?
我真正的问题,在更大的背景下是以下https://gist.github.com/jrm2k6/5962230
最佳答案
您无法有效从回调中返回
您的代码。
在回调中使用
return
不会向您的代码返回值。fs.readFile()
调用回调本身,以便为其提供return
值。为了让您的代码接收它,fs.readFile()
必须返回
从回调中获得的值,但事实并非如此。而且,由于
fs.readFile()
是异步的,所以实际上不能。您的代码跨越 2 个不同的时间点:“现在”
var content; var f = fs.readFile('./index.html', /* ... */); f();
“ future ”
/* ... */ function read(err, data) { if (err) { throw err; } content = data; return console.log(content); } /* ... */
您根本无法在“现在”中使用“ future ”中的值,或者此时的“过去”中的值。
这通常会导致继续使用回调
模式,而不是使用返回
。带着你的"real" code :
var cheerioURLContent = function (url, callback) {
rest.get(url).on("complete", function (result) {
callback(cheerio.load(result));
});
};
cheerioURLContent('./index.html', function (t) {
console.log(t);
});
关于node.js - 如何从回调中返回一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17559698/