# als-promises

> Efficient batch processing and management of promise queues with error handling.

Latest version **2.0.1** (published 2024-02-09) · ISC license · 0 weekly downloads

## Install

```sh
npm install als-promises
pnpm add als-promises
yarn add als-promises
bun add als-promises
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.0.1 |
| Published | 2024-02-09 |
| First published | 2023-12-09 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 13.7 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Alex Sorkin |
| Maintainers | alexsorkin |
| Keywords | promise, batch-processing, asynchronous, promise-management, concurrency, rate-limiting, performance, async-await, error-handling, queue-management |

## Links

- npm: https://www.npmjs.com/package/als-promises
- npm.io page: https://npm.io/package/als-promises

## Alternatives

- [promise-throttle](https://npm.io/package/promise-throttle.md) — 44.2K weekly downloads
- [@commercetools/sync-actions](https://npm.io/package/@commercetools/sync-actions.md) — 25.1K weekly downloads
- [cwait](https://npm.io/package/cwait.md) — 21.4K weekly downloads
- [@ledgerhq/hw-app-cosmos](https://npm.io/package/@ledgerhq/hw-app-cosmos.md) — 4.2K weekly downloads
- [@financial-times/o-loading](https://npm.io/package/@financial-times/o-loading.md) — 2.8K weekly downloads

## Recent versions

- 2.0.1 (latest) — 2024-02-09
- 2.0.0 — 2024-02-09
- 1.1.0 — 2024-02-01
- 1.0.0 — 2023-12-09

## README

# als-promises

- [als-promises](#als-promises)
  - [Change log for v2](#change-log-for-v2)
  - [Overview](#overview)
    - [Browser Compatibility](#browser-compatibility)
    - [Functionality](#functionality)
  - [Usage](#usage)
    - [Validation](#validation)
    - [Getters and Setters](#getters-and-setters)
    - [Parameters](#parameters)
    - [Returns](#returns)
    - [Example](#example)
  - [Handling Nested Promises](#handling-nested-promises)
    - [Correct Usage](#correct-usage)
    - [Incorrect Usage](#incorrect-usage)
  - [Notes](#notes)

## Change log for v2
* Code refactoring and improvement
* Getters and setters for default batch size

## Overview

The `Promises` function is designed to manage and optimize the execution of a large number of asynchronous operations, such as promises, by batching them. This approach is particularly useful for scenarios involving resource-intensive tasks, like file operations or network requests, where you need to avoid overloading the system.

### Browser Compatibility

The `Promises` function is compatible with most modern web browsers. This includes the latest versions of Google Chrome, Mozilla Firefox, Safari, and Microsoft Edge. The function uses ECMAScript 6 (ES6) features like async/await, which are widely supported in these browsers.

### Functionality

- **Batches Asynchronous Operations**: The function groups promises into batches to limit the number of concurrent operations.
- **Queue Management**: It uses an internal queue to manage these batches, ensuring that each batch is processed sequentially.
- **Error Handling**: The function handles errors gracefully. If a promise within a batch fails, it does not stop the processing of other promises in the same batch.
- **Results and Errors**: The function returns an object containing two arrays: one for successful results and another for errors.

## Usage

```js
const promises = require('als-promises')
// <script src="/node_modules/als-promises/promises.js"></script> for browser

// Getters and setters
promises.defSize = 30
promises.defSize // 30 (default is 100)
promises.queue
promises.inProgress

// Usage
promises(arrayOfPromises,batchSize,results,errors) // returns promise
```

### Validation

The function includes validation checks to ensure that:
- `promises` is an array.
- `batchSize` is a positive number.
- `results` and `errors` are arrays, if provided.

These checks help in avoiding common mistakes and ensure smooth functioning of the batch processing.

### Getters and Setters

The function provides getters and setters for managing its internal state:

- `defSize`: Get or set the default batch size. 
  - This value is used as the default number of promises to process simultaneously within a batch. Adjusting this value can be useful for tuning performance based on the specific nature of the tasks and system capabilities.
- `queue`: Get the current state of the queue, including pending batches.
- `inProgress`: Determine if the processing is currently active. 

These properties can be accessed and modified as needed to adjust the behavior of the function dynamically.

### Parameters

- `promises`: An array of functions that return promises. These functions are executed to generate the promises.
- `batchSize` (optional, default = 100): The maximum number of promises to process simultaneously within a batch. This value can be adjusted with the `defSize` setter.
- `results` (optional): An array to store the results of successfully resolved promises.
- `errors` (optional): An array to store the errors from rejected promises.

### Returns

- The function returns a promise that resolves to an object with the following structure:
  - `results`: An array containing the results of successfully resolved promises.
  - `errors`: An array containing the errors from promises that were rejected.

### Example

```javascript
const fetchPromises = urls.map(url => () => fetch(url));
promises(fetchPromises, 10)
    .then(({ results, errors }) => {
        console.log('Fetched data:', results);
        console.error('Errors:', errors);
    })
    .catch(error => {
        console.error('Unexpected error:', error);
    });
```

In this example, `fetchPromises` is an array of functions returning promises from the `fetch` API, and we are processing these promises in batches of 10. The final result includes arrays of fetched data (`results`) and any errors (`errors`) that occurred during fetching.



## Handling Nested Promises

When using nested promises, it's important to understand how these nested callsto ensure that promises are managed correctly without leading to deadlock or exceeding the intended concurrency limitations.

### Correct Usage

**Example: Independent Operations**

In scenarios where nested operations are independent and do not need to wait for each other, you can safely nest `promises` calls.

```javascript
const batch1 = [asyncOperation1, asyncOperation2];
const batch2 = [asyncOperation3, asyncOperation4];

const outerPromise = promises([
    promises(batch1), // First nested call
    promises(batch2)  // Second nested call
], 2);

// This setup is safe because batch1 and batch2 are independent.
```

In this example, `batch1` and `batch2` are independent, and thus their concurrency is managed separately without risk of deadlock.

### Incorrect Usage

**Example: Interdependent Operations Leading to Deadlock**

If nested `promises` calls are interdependent and one depends on the completion of the other, this can lead to a deadlock.

```javascript
let resolveOuter;
const outerPromise = new Promise(resolve => {
    resolveOuter = resolve;
});

const innerPromise = promises([() => outerPromise]);

const deadlockPromise = promises([
    () => innerPromise,
    () => new Promise(resolve => resolveOuter(resolve))
], 1);

// This setup can lead to a deadlock as innerPromise waits for outerPromise,
// which in turn is resolved in the second call within deadlockPromise.
```

In this example, a deadlock occurs because `innerPromise` is waiting for `outerPromise` to resolve, which only happens in the second promise within `deadlockPromise`. 

## Notes
* **Performance Considerations**: The optimal `batchSize` can vary based on the specific requirements and system constraints. It may require tuning for optimal performance.
* **Error Handling**: Errors are segregated and do not halt the processing of the entire batch, allowing for the successful completion of other operations.

---
_Source: https://npm.io/package/als-promises · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
