1.0.1 • Published 6 years ago

ts-using v1.0.1

Weekly downloads
1
License
ISC
Repository
-
Last release
6 years ago

ts-using

travis Coverage Status

I really wanted to be able to use the C# pattern of using and IDisposable in typescript.

using-statement

IDisposable

So I created a small package which mimics the behaviour.

$ npm install ts-using

This will you the following possibility.

function using<T extends Disposable>(val: T, fn: (val: T) => void): Promise<void> | void

Example

Here is an example of how to use it.

Extend the abstract class of Disposable, which forces you to implement dispose() somewhere in your class heriachy.

import { Disposable } from "ts-using";

class Simple extends Disposable {
    getMeaningOfLife() {
        return 42;
    }

    dispose() {
        // Do something
    }
}

Then it can be used with using, which will ensure that dispose() will be called once out of scope.

import { using } from "ts-using";

using(new Simple(), s => {
    const val = s.getMeaningOfLife();
    console.log(val);
});

Async

It supports using async/await. If the given function returns a promise, then it wait on that before calling dispose().

class Async extends Disposable {
    getMeaningOfLife() {
        return new Promise((resolve, reject) => {
            resolve(42);
        });
    }

    dispose() {
        // Do something
    }
}
using(new Async(), async s => {
    const val = await s.getMeaningOfLife();
    console.log(val);
});

If the given function is async, using will return the promise so you can await/then/catch to your liking.

await using(new Async(), async s => {
    const val = await s.getMeaningOfLife();
    console.log(val);
});

Errors are re-thrown, so you can catch them outside of using.

try {
    await using(new Async(), async s => {
        throw new Error("hello");
    });
} catch (err) {
    // Handle error
}