Skip to content

Instantly share code, notes, and snippets.

@ideadapt
Created June 20, 2016 20:10
Show Gist options
  • Save ideadapt/638f69c07f0f8433a33613ff8fbad22b to your computer and use it in GitHub Desktop.
Save ideadapt/638f69c07f0f8433a33613ff8fbad22b to your computer and use it in GitHub Desktop.
Wait for all event subscribers to complete their event processing
"use strict"
var events = require("events")
var ev = new events.EventEmitter()
var log = console.log.bind(console)
process.on('unhandledRejection', function(reason, p) {
log(`Possibly Unhandled Rejection at: Promise ${p} reason: ${reason}`)
})
process.on('uncaughtException', function(err) {
log(`Caught exception: ${err}`)
})
class API {
static load(timeout) {
return new Promise(function(res) {
setTimeout(res, timeout)
})
}
static save(timeout) {
return new Promise(function(res) {
setTimeout(res, timeout)
})
}
}
class PromiseAll {
constructor(){
this.all = [];
}
add() {
var resolver;
this.all.push(new Promise(function(res){
resolver = res
}))
return resolver
}
waitAll() {
return Promise.all(this.all)
}
}
ev.on("changed", function(waitAll) {
log("#1 rec changed")
var one = waitAll.add()
API.load(4000).then(function() {
log("#1 done")
one()
})
})
ev.on("changed", function(waitAll) {
log("#2 rec changed")
var one = waitAll.add()
API.load(2000).then(function() {
log("#2 done")
one()
})
})
var waitAll = new PromiseAll()
ev.emit("changed", waitAll)
API.save(1000).then(function() {
log("changes saved")
waitAll.waitAll().then(function() {
log("all subscribers handled event")
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment