# ensure

```ts
function ensure(fn: () => Operation<unknown> | void): Operation<void>
```

Run the given function or operation when the current operation
shuts down. This is equivalent to running the function or operation
in a `finally {}` block, but it can help you avoid rightward drift.

### Examples
#### Example 1
```javascript
import { main, ensure } from 'effection';
import { createServer } from 'http';

await main(function*() {
  let server = createServer(...);
  yield* ensure(() => { server.close() });
});
```

Note that you should wrap the function body in braces, so the function
returns `undefined`.

---
#### Example 2
```javascript
import { main, ensure, once } from 'effection';
import { createServer } from 'http';

await main(function*() {
  let server = createServer(...);
  yield* ensure(function* () {
    server.close();
    yield* once(server, 'closed');
  });
});
```

Your ensure function should return an operation whenever you need to do
asynchronous cleanup. Otherwise, you can return `void`

---
### Parameters


**fn**: () => [Operation](https://frontside.com/effection/api/v3/Operation.md)&lt;unknown&gt; | void


a function which returns an [Operation](https://frontside.com/effection/api/v3/Operation.md) or void
### Return Type


[Operation](https://frontside.com/effection/api/v3/Operation.md)&lt;void&gt;

[View code](https://github.com/thefrontside/effection/tree/effection-v3.6.1/lib/ensure.ts#L44)
