In the documentation of autobahnJS is provided the following example to illustrate how to make setup a remote procedure call (RPC):
...
// 3) register a procedure for remoting
function add2(args) {
return args[0] + args[1];
}
session.register('com.myapp.add2', add2);
// 4) call a remote procedure
session.call('com.myapp.add2', [2, 3]).then(
function (res) {
console.log("Result:", res);
}
);
...
What if add2 needs to do some async operation? My idea was that maybe one can could call back another remote function registered in the client that triggered the initial call to backend.add2. Something like this:
...
//backend code
function add2(args) {
setTimeout(function() {
console.log("We are done here");
session.call('client.added', [123])
}, 1000);
return null; // useless, this value is never used
}
session.register('backend.add2', add2);
// client code
session.call('backend.add2', [2, 3]).then(
function (res) {
console.log("Result:", res);
}
);
...
Do you see any better option? This seems a bit cumbersome to me. Ideally add2 would return a promise. But I am not sure whether this is possible over a RPC?
You can return a promise which is then resolved once the async function returns.
From the AutobahnJS API reference page:
function myAsyncFunction(args, kwargs, details) {
var d = new autobahn.when.defer();
setTimeout(function() {
d.resolve("async finished");
}, 1000);
return d.promise;
}