delay-async-destroy.js 659 B

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. module.exports = stream => {
  3. if (stream.listenerCount('error') !== 0) {
  4. return stream;
  5. }
  6. stream.__destroy = stream._destroy;
  7. stream._destroy = (...args) => {
  8. const callback = args.pop();
  9. stream.__destroy(...args, async error => {
  10. await Promise.resolve();
  11. callback(error);
  12. });
  13. };
  14. const onError = error => {
  15. // eslint-disable-next-line promise/prefer-await-to-then
  16. Promise.resolve().then(() => {
  17. stream.emit('error', error);
  18. });
  19. };
  20. stream.once('error', onError);
  21. // eslint-disable-next-line promise/prefer-await-to-then
  22. Promise.resolve().then(() => {
  23. stream.off('error', onError);
  24. });
  25. return stream;
  26. };