Created
September 26, 2017 02:49
-
-
Save Orlandster/6d9acf1b12c83882cf54cb75f3aaa52c to your computer and use it in GitHub Desktop.
promise to stream
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
// by jfriend00 - https://stackoverflow.com/questions/46416433/how-to-resolve-a-promise-multiple-times | |
function getNotifier() { | |
const event = new Event('myEvent'); | |
setTimeout(() => { | |
window.dispatchEvent(event); | |
}, 500); | |
setTimeout(() => { | |
window.dispatchEvent(event); | |
}, 700); | |
let callbackList = []; | |
const notifier = { | |
notify: function(fn) { | |
callbackList.push(fn); | |
} | |
}; | |
window.addEventListener('myEvent', (data) => { | |
// call all registered callbacks | |
for (let cb of callbackList) { | |
cb(data); | |
} | |
}); | |
return notifier; | |
}; | |
// Usage: | |
getNotifier().notify(data => {console.log(data.type)}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment