disposer.js 798 B

123456789101112131415161718192021222324252627282930
  1. 'use strict'
  2. module.exports.disposer = disposer
  3. function disposer (creatorFn, disposerFn, fn) {
  4. const runDisposer = (resource, result, shouldThrow = false) => {
  5. return disposerFn(resource)
  6. .then(
  7. // disposer resolved, do something with original fn's promise
  8. () => {
  9. if (shouldThrow)
  10. throw result
  11. return result
  12. },
  13. // Disposer fn failed, crash process
  14. (err) => {
  15. throw err
  16. // Or process.exit?
  17. })
  18. }
  19. return creatorFn
  20. .then((resource) => {
  21. // fn(resource) can throw, so wrap in a promise here
  22. return Promise.resolve().then(() => fn(resource))
  23. .then((result) => runDisposer(resource, result))
  24. .catch((err) => runDisposer(resource, err, true))
  25. })
  26. }