`@push.rocks/smartpromise` simplifies the use of promises and deferred constructs in TypeScript, offering a set of utility functions that extend native Promise capabilities in specific scenarios. This guide walks you through its functionalities, showcasing how to leverage this library in a TypeScript project.
### Setting Up Your Project
Ensure your TypeScript project is configured to support ES Module syntax. In your `tsconfig.json`, you should have:
Deferred objects in `@push.rocks/smartpromise` give you more control over your promises, allowing for manual resolution or rejection beyond the initial executor function.
For scenarios where multiple asynchronous tasks need to be tracked collectively before proceeding, use `CumulativeDeferred`. It waits for all added promises to resolve.
`@push.rocks/smartpromise` does not directly provide a `promisify` function like Node.js `util` module, but you can easily integrate existing functions or use third-party libraries to convert callback-based functions into promises.
Managing timeouts or long-running promises gets easier with helper functions.
```typescript
import { timeoutWrap, timeoutAndContinue } from '@push.rocks/smartpromise';
async function exampleTimeout() {
const myPromise = new Promise((resolve) => setTimeout(() => resolve('Done!'), 2000));
// Will reject if the promise does not resolve within 1 second
try {
const result = await timeoutWrap(myPromise, 1000);
console.log(result);
} catch (error) {
console.error('Promise timed out');
}
// Continues after 1 second, regardless of whether the promise has resolved
const result = await timeoutAndContinue(myPromise, 1000);
console.log(result); // May log `null` if the original promise did not resolve in time
}
exampleTimeout();
```
#### Map and Reduce Asynchronous Functions
Suppose you have a collection of items that you need to process asynchronously. You can use the `map` function to apply an asynchronous function to each item in the array and wait for all the promises to resolve.
```typescript
import { map } from '@push.rocks/smartpromise';
async function processData(items: string[]): Promise<string[]> {
return map(items, async (item) => {
// Simulate an async operation
await new Promise((resolve) => setTimeout(resolve, 100));
If you have multiple deferred objects and you want to manage them collectively, you can do so using the `CumulativeDeferred` class. This is especially useful when you have a dynamic number of deferreds to resolve.
```typescript
import { defer, cumulativeDefer } from '@push.rocks/smartpromise';
async function exampleComplexDeferred(): Promise<void> {
new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 1000)),
new Promise<boolean>((resolve) => setTimeout(() => resolve(true), 2000)),
]);
console.log(raceResults); // Outputs: true
console.log('Complete Use Case Example Finished!');
}
completeUseCaseExample();
```
### Testing Your Code
Testing is crucial to ensure the reliability of your asynchronous workflows. You can write tests using the `@push.rocks/tapbundle` library to create unit tests for your promises and deferred constructs.
```typescript
import { tap, expect } from '@push.rocks/tapbundle';
import * as smartpromise from '@push.rocks/smartpromise';
tap.test('should resolve a deferred promise', async () => {
const deferred = smartpromise.defer<string>();
deferred.resolve('Resolved!');
const result = await deferred.promise;
expect(result).toEqual('Resolved!');
});
tap.test('should timeout a long-running promise', async () => {
const longRunningPromise = new Promise((resolve) => setTimeout(resolve, 2000));
tap.test('should map async function to an array', async () => {
const inputArray = ['a', 'b'];
const result = await smartpromise.map(inputArray, async (item) => item.toUpperCase());
expect(result).toEqual(['A', 'B']);
});
tap.start();
```
By following this guide and using the examples provided, you should be able to effectively use `@push.rocks/smartpromise` for managing promises and deferred constructs in your TypeScript project. The library's extensive utility functions, combined with TypeScript support, make it a powerful tool for modern asynchronous programming needs.
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.