You can't usefully return
from within the callback to your code.
Using return
inside the callback doesn't return a value to your code. fs.readFile()
calls the callback itself so the return
value is given to it. For your code to receive it, fs.readFile()
would have to return
the value it got from the callback, which it doesn't.
And, since fs.readFile()
is asynchronous, it actually can't. Your code spans 2 different points in time:
"Present"
var content;
var f = fs.readFile('./index.html', /* ... */);
f();
"Future"
/* ... */
function read(err, data) {
if (err) {
throw err;
}
content = data;
return console.log(content);
}
/* ... */
You simply can't use a value from the "Future" in the "Present" -- or, at that point, the "Past."
This all generally leads to continuing the callback
pattern rather than using return
. Taking your "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);
});