Last active
March 10, 2017 21:23
-
-
Save burdiuz/95bef6991b46839f081aa501ede00ce0 to your computer and use it in GitHub Desktop.
Dispatches event and wait for response event and resolve promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SymbolImpl from 'SymbolImpl'; | |
import EventDeferred from 'EventDeferred'; | |
const INTERNALS_FIELD = SymbolImpl('duplex.listener::internals'); | |
class DuplexListener { | |
constructor(dispatcher, event, responseEventType, data = null) { | |
if (responseEventType) { | |
const deferred = new EventDeferred(dispatcher, responseEventType); | |
this.promise = deferred.promise; | |
this[INTERNALS_FIELD] = deferred; | |
} else { | |
this.promise = Promise.resolve(); | |
} | |
// INFO This kind of dispatchEvent signature is used | |
// with https://github.com/burdiuz/js-event-dispatcher | |
dispatcher.dispatchEvent(event, data); | |
} | |
get listening() { | |
return this[INTERNALS_FIELD] && this[INTERNALS_FIELD].listening || false; | |
} | |
cancel = () => { | |
this[INTERNALS_FIELD] && this[INTERNALS_FIELD].cancel(); | |
}; | |
dispose = () => { | |
this[INTERNALS_FIELD] && this[INTERNALS_FIELD].dispose(); | |
delete this[INTERNALS_FIELD]; | |
}; | |
} | |
// resolver(eventType:string):string is a function that returns type of response event | |
export const requestResolverFactory = (resolver) => { | |
return (dispatcher) => { | |
return (eventType, data = null) => { | |
const deferred = new DuplexListener(dispatcher, eventType, resolver(eventType), data); | |
return deferred.promise; | |
}; | |
}; | |
}; | |
export default DuplexListener; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "DuplexListener", | |
"description": "Dispatches event and wait for response event and resolve promise", | |
"version": "0.0.1", | |
"main": "DuplexListener.js", | |
"dependencies": { | |
"SymbolImpl": "https://gist.github.com/burdiuz/7664491eed84695250e46be20670be84", | |
"EventDeferred": "https://gist.github.com/burdiuz/fc54775c907422386fbcad2cf701ab0d" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment