@@ -45,7 +45,6 @@ export class __TS__Promise<T> implements Promise<T> {
4545
4646 private fulfilledCallbacks : Array < PromiseResolve < T > > = [ ] ;
4747 private rejectedCallbacks : PromiseReject [ ] = [ ] ;
48- private finallyCallbacks : Array < ( ) => void > = [ ] ;
4948
5049 // @ts -ignore
5150 public [ Symbol . toStringTag ] : string ; // Required to implement interface, no output Lua
@@ -124,16 +123,23 @@ export class __TS__Promise<T> implements Promise<T> {
124123 }
125124
126125 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
126+ // Delegates to .then() so that a new Promise is returned (per ES spec §27.2.5.3)
127+ // and the original fulfillment value / rejection reason is preserved.
127128 public finally ( onFinally ?: ( ) => void ) : Promise < T > {
128- if ( onFinally ) {
129- this . finallyCallbacks . push ( onFinally ) ;
130-
131- if ( this . state !== PromiseState . Pending ) {
132- // If promise already resolved or rejected, immediately fire finally callback
133- onFinally ( ) ;
134- }
135- }
136- return this ;
129+ return this . then (
130+ onFinally
131+ ? ( value : T ) : T => {
132+ onFinally ( ) ;
133+ return value ;
134+ }
135+ : undefined ,
136+ onFinally
137+ ? ( reason : any ) : never => {
138+ onFinally ( ) ;
139+ throw reason ;
140+ }
141+ : undefined
142+ ) ;
137143 }
138144
139145 private resolve ( value : T | PromiseLike < T > ) : void {
@@ -168,25 +174,13 @@ export class __TS__Promise<T> implements Promise<T> {
168174
169175 private invokeCallbacks < T > ( callbacks : ReadonlyArray < ( value : T ) => void > , value : T ) : void {
170176 const callbacksLength = callbacks . length ;
171- const finallyCallbacks = this . finallyCallbacks ;
172- const finallyCallbacksLength = finallyCallbacks . length ;
173177
174178 if ( callbacksLength !== 0 ) {
175179 for ( const i of $range ( 1 , callbacksLength - 1 ) ) {
176180 callbacks [ i - 1 ] ( value ) ;
177181 }
178182 // Tail call optimization for a common case.
179- if ( finallyCallbacksLength === 0 ) {
180- return callbacks [ callbacksLength - 1 ] ( value ) ;
181- }
182- callbacks [ callbacksLength - 1 ] ( value ) ;
183- }
184-
185- if ( finallyCallbacksLength !== 0 ) {
186- for ( const i of $range ( 1 , finallyCallbacksLength - 1 ) ) {
187- finallyCallbacks [ i - 1 ] ( ) ;
188- }
189- return finallyCallbacks [ finallyCallbacksLength - 1 ] ( ) ;
183+ return callbacks [ callbacksLength - 1 ] ( value ) ;
190184 }
191185 }
192186
0 commit comments