fast-csv icon indicating copy to clipboard operation
fast-csv copied to clipboard

[FEATURE] allow async event handler functions

Open andrisi opened this issue 3 years ago • 3 comments

Is your feature request related to a problem? Please describe. Using async event handlers. Most of my code uses sync function and need to be called with await.

Describe the solution you'd like If an event handler returns a promise, wait on it.

Describe alternatives you've considered Calling async functions from sync code, ...

andrisi avatar Jul 20 '21 11:07 andrisi

Any update on this @doug-martin or @dustinsmith1024 - seems like an easy addition but something that would help using standard await/async construncts in modern js. Thanks a lot. Or maybe not that easy because you're not using async functions where you'd need to await event handlers?

andrisi avatar Feb 15 '22 21:02 andrisi

@andrisi You can pause the stream while waiting for async operations, like this:

  const csvStream = fs.createReadStream('file.csv')
    .pipe(csv.parse({ headers: true }))
    .on('data', async (row) => {
      try {
        csvStream.pause();
        await doSomethingAsync(row);
      } finally {
        csvStream.resume();
      }
    })
    .on('end', () => {
      
    });

pigpudle avatar Jun 23 '23 10:06 pigpudle

Thanks @pigpudle good workaround, will use it! Handling async event handlers properly on the other hand - with all events -would be cleaner and in line with what you'd expect when you add an async event handler. It's easy to detect that the result of the event handler function is a promise. Or it's handled outside of your code? I got to learn more about streams...

andrisi avatar Jun 23 '23 10:06 andrisi