Skip to content

Instantly share code, notes, and snippets.

@amackintosh
Created September 4, 2017 01:24
Show Gist options
  • Save amackintosh/8b43b5f070493a0abcfc9c3ce216edfc to your computer and use it in GitHub Desktop.
Save amackintosh/8b43b5f070493a0abcfc9c3ce216edfc to your computer and use it in GitHub Desktop.
To control when and how to fire logic, we can use event emitters.
const fs = require('fs')
const EventEmitter = require('events')
const lazy = new EventEmitter()
const someTask = async () => true
const anotherTask = async () => true
const files = ['file1.txt', 'file2.txt', 'file3.txt']
const readFile = (file) => {
try {
return new Promise(async (resolve, reject) =>
fs.readFile(file, 'utf8', (err, content) =>
resolve(content)))
} catch (e) {
throw 'readFile# ' + e
}
}
const loadFiles = (files) => {
try {
if (!files) return false
return Promise.all(files.reduce((all, file) => {
all.push(readFile(file))
return all
}, []))
} catch (e) {
throw 'loadFiles# ' + e
}
}
const startApp = async () => {
try {
await someTask()
await anotherTask()
return lazy.on('getFiles', async () => {
const onceReady = await loadFiles(files)
console.log(`Additional logic and: ${JSON.stringify(onceReady, null, 2)}`)
})
} catch (e) {
throw 'startApp# ' + e
}
}
startApp()
.then((maybeUseFiles) => {
setTimeout(() => {
// Whenever you feel like, trigger the aftermarket mods
lazy.emit('getFiles')
}, (Math.random()*1000))
})
.catch((meltdown) => {
console.error(new Error('MELTDOWN DETECTED: ' + meltdown))
process.exit(1)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment