Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
Is it lecit to pass an event emitter to a function?

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?

  1. 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
}
  1. 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;
  }
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!