es.promise.finally.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var IS_PURE = require('../internals/is-pure');
  4. var NativePromise = require('../internals/native-promise-constructor');
  5. var fails = require('../internals/fails');
  6. var getBuiltIn = require('../internals/get-built-in');
  7. var speciesConstructor = require('../internals/species-constructor');
  8. var promiseResolve = require('../internals/promise-resolve');
  9. var redefine = require('../internals/redefine');
  10. // Safari bug https://bugs.webkit.org/show_bug.cgi?id=200829
  11. var NON_GENERIC = !!NativePromise && fails(function () {
  12. NativePromise.prototype['finally'].call({ then: function () { /* empty */ } }, function () { /* empty */ });
  13. });
  14. // `Promise.prototype.finally` method
  15. // https://tc39.github.io/ecma262/#sec-promise.prototype.finally
  16. $({ target: 'Promise', proto: true, real: true, forced: NON_GENERIC }, {
  17. 'finally': function (onFinally) {
  18. var C = speciesConstructor(this, getBuiltIn('Promise'));
  19. var isFunction = typeof onFinally == 'function';
  20. return this.then(
  21. isFunction ? function (x) {
  22. return promiseResolve(C, onFinally()).then(function () { return x; });
  23. } : onFinally,
  24. isFunction ? function (e) {
  25. return promiseResolve(C, onFinally()).then(function () { throw e; });
  26. } : onFinally
  27. );
  28. }
  29. });
  30. // patch native Promise.prototype for native async functions
  31. if (!IS_PURE && typeof NativePromise == 'function' && !NativePromise.prototype['finally']) {
  32. redefine(NativePromise.prototype, 'finally', getBuiltIn('Promise').prototype['finally']);
  33. }