Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RPC with promises for node.js [closed]

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');
});
like image 351
bara Avatar asked Feb 11 '14 17:02

bara


People also ask

How do you deal with promises in Node?

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 .

Does Nodejs have promises?

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.

Does Promise block JavaScript?

When using Javascript promises, does the event loop get blocked? No. Promises are only an event notification system. They aren't an operation themselves.

How many promises can Node js handle?

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.


1 Answers

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');
})();
like image 86
brillout Avatar answered Oct 04 '22 20:10

brillout