async.js 806 B

1234567891011121314151617181920212223242526272829
  1. 'use strict'
  2. // https://github.com/jprichardson/node-fs-extra/issues/1056
  3. // Performing parallel operations on each item of an async iterator is
  4. // surprisingly hard; you need to have handlers in place to avoid getting an
  5. // UnhandledPromiseRejectionWarning.
  6. // NOTE: This function does not presently handle return values, only errors
  7. async function asyncIteratorConcurrentProcess (iterator, fn) {
  8. const promises = []
  9. for await (const item of iterator) {
  10. promises.push(
  11. fn(item).then(
  12. () => null,
  13. (err) => err ?? new Error('unknown error')
  14. )
  15. )
  16. }
  17. await Promise.all(
  18. promises.map((promise) =>
  19. promise.then((possibleErr) => {
  20. if (possibleErr !== null) throw possibleErr
  21. })
  22. )
  23. )
  24. }
  25. module.exports = {
  26. asyncIteratorConcurrentProcess
  27. }