es.promise.finally.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var IS_PURE = require('../internals/is-pure');
  4. var NativePromiseConstructor = require('../internals/promise-native-constructor');
  5. var fails = require('../internals/fails');
  6. var getBuiltIn = require('../internals/get-built-in');
  7. var isCallable = require('../internals/is-callable');
  8. var speciesConstructor = require('../internals/species-constructor');
  9. var promiseResolve = require('../internals/promise-resolve');
  10. var redefine = require('../internals/redefine');
  11. var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype;
  12. // Safari bug https://bugs.webkit.org/show_bug.cgi?id=200829
  13. var NON_GENERIC = !!NativePromiseConstructor && fails(function () {
  14. // eslint-disable-next-line unicorn/no-thenable -- required for testing
  15. NativePromisePrototype['finally'].call({ then: function () { /* empty */ } }, function () { /* empty */ });
  16. });
  17. // `Promise.prototype.finally` method
  18. // https://tc39.es/ecma262/#sec-promise.prototype.finally
  19. $({ target: 'Promise', proto: true, real: true, forced: NON_GENERIC }, {
  20. 'finally': function (onFinally) {
  21. var C = speciesConstructor(this, getBuiltIn('Promise'));
  22. var isFunction = isCallable(onFinally);
  23. return this.then(
  24. isFunction ? function (x) {
  25. return promiseResolve(C, onFinally()).then(function () { return x; });
  26. } : onFinally,
  27. isFunction ? function (e) {
  28. return promiseResolve(C, onFinally()).then(function () { throw e; });
  29. } : onFinally
  30. );
  31. }
  32. });
  33. // makes sure that native promise-based APIs `Promise#finally` properly works with patched `Promise#then`
  34. if (!IS_PURE && isCallable(NativePromiseConstructor)) {
  35. var method = getBuiltIn('Promise').prototype['finally'];
  36. if (NativePromisePrototype['finally'] !== method) {
  37. redefine(NativePromisePrototype, 'finally', method, { unsafe: true });
  38. }
  39. }