事件触发时触发Promise

我的整个项目都使用(Bluebird)Promises,但是有一个使用EventEmitter的特定库。

我想要实现以下目标:

Promise.on('connect', function() {

x.doSomething();

}).then(function() {

return new Promise(function(resolve) {

y.doAction(resolve); // this will result in `eventB` getting emitted

});

}).on('eventB', function() {

z.handleEventB();

}).then(function() {

z.doSomethingElse();

});

我在Promises链中读了EventEmitter的答案。这给了我一种执行’connect’事件的回调的方法。这是我到目前为止所到之处

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); // this will result in eventB getting emitted

});

});

现在如何进一步链接“ eventB”?

回答:

我假设您想为每个事件做不同的事情。即使eventB由的动作触发connect,您也可以将其视为另一种逻辑流。

旁注:为避免对您和其他必须阅读此代码库的人造成混淆,我建议您不要使用其他方法来补充Promise,除非您 详尽地记录了它们。

从您的示例来看,似乎可以进行以下操作。

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(){

return x.doSomething()

}).then( function(){

return y.doSomethingElse() // will trigger `eventB` eventually

})

// this promise stream will begin once `eventB` has been triggered

eventBHappened.then( function(){

return z.doSomething()

})

如果您想简化此常数

var p = new Promise( function( resolve ){

emitter.on( 'something', resolve )

})

你可以用这样的东西

function waitForEvent( emitter, eventType ){

return new Promise( function( resolve ){

emitter.on( eventType, resolve )

})

}

这将上面的代码解决方案变成

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(){

return x.doSomething()

}).then( function(){

return y.doSomethingElse() // will trigger `eventB` eventually

})

// this promise stream will begin once `eventB` has been triggered

waitForEvent( emitter, 'eventB' ).then( function(){

return z.doSomething()

})

并且由于Javascript中的函数捕获了定义它们的范围,因此可以将该代码进一步简化为

var Promise = require( 'bluebird' )

var emitter = someEmitter()

function waitForEvent( type ){

return new Promise( function( resolve ){

//emitter has been captured from line #2

emitter.on( type, resolve )

})

}

waitForEvent( 'connect' ).then( function(){

return x.doSomething()

}).then( function(){

return y.doSomethingElse() // will trigger `eventB` eventually

})

// this promise stream will begin once `eventB` has been triggered

waitForEvent( 'eventB' ).then( function(){

return z.doSomething()

})

以上是 事件触发时触发Promise 的全部内容, 来源链接: utcz.com/qa/408329.html

回到顶部