finally.js 673 B

123456789101112131415161718192021222324
  1. "use strict";
  2. var ensurePlainFunction = require("type/plain-function/ensure")
  3. , isThenable = require("type/thenable/is")
  4. , ensureThenable = require("type/thenable/ensure");
  5. var resolveCallback = function (callback, next) {
  6. var callbackResult = callback();
  7. if (!isThenable(callbackResult)) return next();
  8. return callbackResult.then(next);
  9. };
  10. module.exports = function (callback) {
  11. ensureThenable(this);
  12. ensurePlainFunction(callback);
  13. return this.then(
  14. function (result) {
  15. return resolveCallback(callback, function () { return result; });
  16. },
  17. function (error) {
  18. return resolveCallback(callback, function () { throw error; });
  19. }
  20. );
  21. };