I am making a kind of communications channel , which sends requests and receives responses.
The function that sends a request, I want it to return a Promise
, which will be resolved by the receiving function (internal to the class).
And that's where I got stuck:
class IOChannel {
constructor( channel ) {
this.$channel = channel;
this.$queue = { };
channel.on( 'message', ( data ) => {
if( 'error' in data ) {
// Es una respuesta con un error. // <- ¿ ?
} else if( 'result' in data ) {
// Es una respuesta. // <- ¿ ?
} );
}
$nextId( ) { ... }
async sendRequest( params ) {
this.$channel.send( {
id: this.$nextId( ),
params: params
} );
return new Promise( ); // <- ¿ ?
}
}
Both outgoing requests and incoming responses are related by the id
message attribute. The idea was to use the variable this.$queue
as a join point between outgoing requests and incoming responses, based on that attribute id
.
But I can't think of how to relate the response callbackmessage
function to the one Promise
generated in the function sendRequest( )
.
How do I have to modify my code so that the function sendMessage( )
returns a valid promise, which will be resolved or rejected by my callback function ?
edit
The intent is to call that function sendRequest( )
from route handlers express
:
const express = require( 'express' );
const app = express( );
const ioChannel = new IOChannel( process );
app.post( '/login', body-parser, function( req, res ) {
const view = await ioChannel.send( {
login: req.body.userId,
pass: req.body.pass
} );
res.status( view ? 200 : 401 ).end( );
}
I think what you need is this:
I've created a simple implementation with the help of this answer that I think may be useful, although it may be far from something usable in production.
The idea is to encapsulate the queue logic
"resolvers"
so that it doesn't have to be handled outside of the public API#on
.It also takes into account that there may be different ones
listeners
for each event and the promise that the method returnssend
resolves when all the listeners finish their task.