Created
September 4, 2017 01:24
-
-
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.
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
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