@wmfs/statebox
Version:
Orchestrate Node functions using Amazon States Language
57 lines (45 loc) • 1.24 kB
JavaScript
const Status = require('./Status')
class Latch {
constructor () {
this.promise_ = new Promise(resolve => {
this.trigger_ = (result) => resolve(result)
})
}
promise () {
return this.promise_
}
fire (result) {
this.trigger_(result)
}
} // class Latch
function makeLatch () {
return new Latch()
}
class CallbackManager {
constructor () {
this.callbacks = {}
}
addCallback (eventName, executionName) {
const latch = makeLatch()
this.callbacks[executionName] = {
eventName: eventName,
timestamp: new Date(),
latch: latch
}
return latch.promise()
} // addCallback
fireCallback (eventName, executionName, output) {
if (!this.hasEvent(eventName, executionName)) {
return
}
const latch = this.callbacks[executionName].latch
delete this.callbacks[executionName]
latch.fire(output)
} // fireCallback
hasEvent (eventName, executionName) {
return Object.prototype.hasOwnProperty.call(this.callbacks, executionName) &&
(this.callbacks[executionName].eventName === eventName ||
eventName === Status.COMPLETE) // if complete, fire any callback
} // hasEvent
} // CallbackManager
module.exports = CallbackManager