All files / src/impl CompleteNow.impl.ts

100% Statements 15/15
100% Branches 0/0
100% Functions 1/1
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 3712x     12x                       12x 18x   17x 17x   17x   17x 17x 12x 12x   5x 5x 5x   17x        
import { Supplier, Type as SupplierType, fromType as fromTypeToSupplier } from "@jonloucks/concurrency-ts/auxiliary/Supplier";
import { RequiredType, OptionalType, Throwable } from "@jonloucks/concurrency-ts/api/Types";
import { OnCompletion } from "@jonloucks/concurrency-ts/api/OnCompletion";
import { onCompletionCheck } from "@jonloucks/concurrency-ts/auxiliary/Checks";
import { CompletionState } from "@jonloucks/concurrency-ts/api/CompletionState";
 
/**
 * Completes the given OnCompletion immediately with the result of the successBlock.
 * If the successBlock throws, the OnCompletion is completed with FAILED state.
 *
 * @param onCompletion The OnCompletion to complete
 * @param successBlock The block to execute to obtain the success value
 * @returns The value returned by the successBlock if successful, otherwise undefined
 * @throws Rethrows any exception thrown by the successBlock
 */
export function completeNow<T>(onCompletion: RequiredType<OnCompletion<T>>, successBlock: RequiredType<SupplierType<T>>): OptionalType<T> {
  const validOnCompletion = onCompletionCheck(onCompletion); // only validate onCompletion here
  let state!: CompletionState;
  let thrown: OptionalType<Throwable<unknown>> = undefined;
  let value: OptionalType<T> = undefined;
 
  try {
    // validate and execute successBlock
    const validSupplier: Supplier<T> = fromTypeToSupplier(successBlock);
    value = validSupplier.supply();
    state = 'SUCCEEDED';
    return value;
  } catch (caught) {
    thrown = caught;
    state = 'FAILED';
    throw thrown;
  } finally {
    validOnCompletion.onCompletion({ state, thrown, value });
  }
}