npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

als-promises

v2.0.1

Published

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

Downloads

19

Readme

als-promises

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

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

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.

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.

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.