Difficulty in understanding Meteor.wrapAsync

Meteor.methods({
  'wrapTest': function() {
    var fs = Npm.require('fs');
    getFileContents = function(callback) {
      fs.readFile('/Users/anoop/delete/juhi.txt', 'utf8', function(err, res) {
	if (err) console.log(err);
	else callback && callback( null, res + 'modified' );
      });
    };
    var getFileContentsSynchronously =  Meteor.wrapAsync(getFileContents); 
    var result = getFileContentsSynchronously();
    console.log(result);
    return result;
  }
});

Calling the above method logs { file contents + ‘modified’ } to console.

We are not passing any callback function when creating var getFileContentsSynchronously or when calling it
my confusion is how does the else block above know what function definition to use when calling

callback( null, res + 'modified')

wrapAsync assumes the convention of the wrapped function signature being (optionalParameters, callback) with the callback signature being (error, result). In your example, your getFileContents function has no parameters, but does have a callback with an (error, result) signature (so it conforms to the assumption).

Normally, the required function would be wrapped more closely, which perhaps makes it clearer:

getFileContents = Meteor.wrapAsync(fs.readFile, fs); // assumed final callback(error, result)
try {
  var result = getFileContentsSynchronously('/Users/anoop/delete/juhi.txt', 'utf8');
} catch (error) {
  ...
}
1 Like
    var fs = Npm.require('fs');
    var fs_sync = Meteor.wrapAsync(fs.readFile, fs);
    
    var fileContents = fs_sync ('/Users/anoop/delete/juhi.txt', 'utf8');
    console.log(fileContents);

So, wrapAsync makes the following modifications to ‘fs’:

Whatever result value that ‘fs’ used to pass to its callback will now be the return value of fs_sync. Right?

Thank you very much Rob

1 Like

Correct, and if there’s an error, it will be thrown (which is the reason for the try/catch).

Now I get it, thank you