UNPKG

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