autobahn JS, what if RPC's callee is async?

605 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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;
}
1
On

My example of registering async function

  session.register('com.forlunch.list_chats', function (args, kwargs, details) {
        return functions.list_chats(args);
    })

which make query to the mysql database

async function list_chats(params){
    var query = "SELECT * WHERE ... ;"
    let res = await mysql_query(query)
    return res
}

function mysql_query (query){
  return new Promise(function(resolve, reject) {
    const con =  mysql.createConnection(mysql_options);
    con.query(query,[], function (err, rows, fields) {
        if (err) return reject(err);
        resolve(rows);
    });
  })
}