node.js - Trigger Promise when an event fires -
my entire project uses (bluebird) promises, there's 1 particular library uses eventemitter.
i want achieve like:
promise.on('connect', function() { x.dosomething(); }).then(function() { return new promise(function(resolve) { y.doaction(resolve); // result in `eventb` getting emitted }); }).on('eventb', function() { z.handleeventb(); }).then(function() { z.dosomethingelse(); });
i read answer eventemitter in middle of chain of promises. gives me way execute callback 'connect' event. here's have got far
var p = new promise(function(resolve) { emitter.on('connect', resolve); }); p.on = function() { emitter.on.apply(emitter, arguments); return p; }; p.on('connect', function() { x.dosomething(); }).then(function() { return new promise(function(resolve) { y.doaction(resolve); // result in eventb getting emitted }); });
now how chain further 'eventb' ?
i assume want different chain of things each event. if eventb
triggered actions of connect
, can treat stream of logic.
side note: avoid confusion , else has read codebase, i'd recommend against supplementing promises additional methods unless very thorough documenting them.
from example, seems following work.
var promise = require( 'bluebird' ) var emitter = someemitter() var connected = new promise( function( resolve ){ emitter.on( 'connect', resolve ) }) var eventbhappened = new promise( function( resolve ){ emitter.on( 'eventb', resolve ) }) connected.then( function(){ x.dosomething() }).then( function(){ y.dosomethingelse() // trigger `eventb` }) // promise stream begin once `eventb` has been triggered eventbhappened.then( function(){ z.dosomething() })
if you'd simplify constant
var p = new promise( function( resolve ){ emitter.on( 'something', resolve ) })
you can use this
function waitforevent( emitter, eventtype ){ return new promise( function( resolve ){ emitter.on( eventtype, resolve ) }) }
which turns code solution above into
var promise = require( 'bluebird' ) var emitter = someemitter() function waitforevent( eventemitter, eventtype ){ return new promise( function( resolve ){ eventemitter.on( eventtype, resolve ) }) } waitforevent( emitter, 'connect' ).then( function(){ x.dosomething() }).then( function(){ y.dosomethingelse() // trigger `eventb` }) // promise stream begin once `eventb` has been triggered waitforevent( emitter, 'eventb' ).then( function(){ z.dosomething() })
and because functions in javascript capture scope defined, code further simplified to
var promise = require( 'bluebird' ) var emitter = someemitter() function waitforevent( type ){ return new promise( function( resolve ){ //emitter has been captured line #2 emitter.on( type, resolve ) }) } waitforevent( 'connect' ).then( function(){ x.dosomething() }).then( function(){ y.dosomethingelse() // trigger `eventb` }) // promise stream begin once `eventb` has been triggered waitforevent( 'eventb' ).then( function(){ z.dosomething() })
Comments
Post a Comment