I'm trying to make a call over WAMP to a remote function. But I don't know how to write the called function if it has asynchronous behavior. In every example I've seen the remote function returns the result. How can this be done in an asynchronous manner where I would normally use a callback?
Example: This is the registration of a function that would get the contents of a file asynchronously.
session.register('com.example.getFileContents', getFileContents).then(
function (reg) {
console.log("procedure getFileContents() registered");
},
function (err) {
console.log("failed to register procedure: " + err);
}
);
Here is how I would call that function remotely.
session.call('com.example.getFileContents', ["someFile.txt"]).then(
function (res) {
console.log("File Contents:", res);
},
function (err) {
console.log("Error getting file contents:", err);
}
);
But here is the actual function that was registered.
function getFileContents(file) {
fs.readFile(file, 'utf8', function(err, data) {
// How do I return the data?
});
}
How do I return the data from getFileContents so that it can be sent back over the WAMP connection? I know I could use readFileSync and return what it returns. But I'm specifically asking how to do this in an asynchronous manner.
I figured out how to do this with promises. Here is how the function implemented with promises.
var fs = require('fs');
var when = require('when');
function getFileContents(file) {
var d = when.defer();
fs.readFile(file, 'utf8', function(err, data) {
d.resolve(data);
});
return d.promise;
}