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'); });
The promise is resolved by calling resolve() if the promise is fulfilled, and rejected by calling reject() if it can't be fulfilled. Both resolve() and reject() takes one argument - boolean , string , number , array , or an object .
A Promise in Node means an action which will either be completed or rejected. In case of completion, the promise is kept and otherwise, the promise is broken. So as the word suggests either the promise is kept or it is broken. And unlike callbacks, promises can be chained.
When using Javascript promises, does the event loop get blocked? No. Promises are only an event notification system. They aren't an operation themselves.
Assuming we have the processing power and that our promises can run in parallel, there is a hard limit of just over 2 million promises. If we dig into the code of V8, the JavaScript engine underlying Chrome and Node.
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');
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With