Suppose I have this example:
function transform(data) {
const out = new EventEmitter();
async function run() {
try {
const url = await initialise();
const data = await downloadFile(url);
out.emit('data', data);
} catch(err) {
out.emit('error', err);
}
}
async function initialise() {
const req = superagent.post('url...')
superagent.send(data)
const res = await req // this will actually fire the request
out.emit('initialize')
return res.body
}
async function downloadFile(url) {
const req = superagent.put(url)
req.on('progress', (progress) => out.emit('downloadFile', progress)
const res = await req; // this will actually fire the request
//
// save to disk
//
return data;
}
run();
return out;
}
(https://stackoverflow.com/a/48794504/3154403)
Then, suppose I would like to have another function stuff() that will be called by downloadFile(). stuff() would do some things I would like to notify.
What's the best option?
- Pass the emitter to
stuff()
async function stuff(emitter) {
let var
var = await task1()
emitter.emit('task1', var)
var = await task2()
emitter.emit('task2', var)
var = await task3()
emitter.emit('task3', var)
return var
}
- or have
stuff()returning a new emitter and listening on it?
async function downloadFile(url) {
const req = superagent.put(url)
req.on('progress', (progress) => out.emit('downloadFile', progress)
const res = await req; // this will actually fire the request
stuff().on('task1', var => out.emit('task1', var)
// eventual other listeners
return data;
}