All files / src/utils promise.ts

77.77% Statements 7/9
25% Branches 1/4
60% Functions 3/5
77.77% Lines 7/9

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    4x   4x 37x   37x   37x   37x                       37x              
export type Cancellable<T> = { promise: PromiseLike<T>; cancel: () => void }
 
export class CancellableError extends Error {}
 
export function makeCancellable<T>(promise: PromiseLike<T>): Cancellable<T> {
    let hasCanceled_ = false
 
    const wrappedPromise = new Promise<T>((resolve, reject) => {
        // eslint-disable-next-line promise/prefer-await-to-then
        return promise.then(
            val => 
                hasCanceled_
                    ? reject(new CancellableError("cancelled promise"))
                    : resolve(val)
            ,
            error => 
                hasCanceled_
                    ? reject(new CancellableError("cancelled promise"))
                    : reject(error)
            
        )
    })
 
    return {
        promise: wrappedPromise,
        cancel() {
            hasCanceled_ = true
        },
    }
}