I have this function:
exports.readPartial = function(html, values, response) {
fs.readFile(__dirname + "/../html/partials/" + html, function(error, file) {
if(error) { this.loadError(response, error); }
else {
console.log("\t--> partial found: " + file);
return file; // FILE VALUE
}
});
}
When that function is called it should return the value of “file”. However, when calling return file; im actually returning the value in the anonymous function I passed as an argument.
What is the right way to return this value on async programming with nodejs?
Using var that = this; ?
Got confused pretty confused with this style of programming.
Your
readPartialfunctions relies on an asynchronous functionreadFile. So it gets asynchronous, too.Now you have several options on how to solve this problem:
fs.readFile, which isfs.readFileSync(see http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_encoding). Then you are able to return the result as usual.So, basically this means: Either both functions have to be asynchronous, or both need to be synchronous.
Of these two options, I’d prefer the asynchronous one to use a callback as well: This is exactly what is Node.js’ core competency – asynchronous, non-blocking I/O. So if you do not have strong reasons against it, stick with the asynchronous version and use callbacks.
Of course, you may be interested in what other options exist. So, here they are (ALTHOUGH I WOULD NOT RECOMMEND IT):
fs.readFileand “wait” for its callback to return. This basically means active waiting with awhile(true)loop, and is definitely considered bad practice. Anyway, technically it is viable. For the rare case you really want to do this, or you are simply interested in how one might implement something like this, check out syncasync.js.