RPC with promises for node.js
javascript, node.js, promise, rpc, websocket
Solution
I've written an RPC implementation called Wildcard API that lets you do just that:
// Node.js server
const { server } = require('@wildcard-api/server');
// We define a `timeout` function on the server
server.timeout = function({seconds}) {
await sleep({seconds});
};
function sleep({seconds}) {
return new Promise(resolve => setTimeout(resolve, seconds * 1000));
}
// Browser
import { server } from '@wildcard-api/client';
(async () => {
// Wildcard makes our `timeout` function available in the browser
await server.timeout({seconds: 2});
// 2 seconds later...
console.log('done');
})();
Problem
Are there any RPC modules which work with promises? On the server I have functions which return promises. I would like to expose them for browser clients to call over websockts or fallbacks. I found some RPC libraries for example dnode, but they expect a callback as parameter. I would like something like this: Server: ``` rpc.expose({ timeout: function (time) { var d = Q.defer(); setTimeout(function () { d.resolve(); }, time); return d.promise; } }); ``` Client: ``` rpc.timeout(2000).then(function() { console.log('done'); }); ```