3.0.0 • Published 2 months ago

als-smart-promise v3.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
2 months ago

als-smart-promise

als-smart-promise is a JavaScript utility for managing and executing chains of asynchronous functions with advanced error handling and support for timeouts. It is built to provide a flexible way to create and manage sequences of operations where each step in the sequence can depend on the result of the previous one.

Changes in 3

  • args is a first parameter and not context

Installation

npm install als-smart-promise

Usage

Here's a basic example of how to use als-smart-promise:

const SmartPromise = require('als-smart-promise');

// Define your asynchronous functions
const func1 = async (args,context) => {
    // Your code here
    context.next('result of func1');
};

const func2 = async (args,context, resultFromFunc1) => {
    // Your code here
    context.resolve('final result');
};

// Create a SmartPromise instance
const sp = new SmartPromise([func1, func2]);

// Run the sequence
sp.run().then(result => {
    console.log(result); // 'final result'
}).catch(error => {
    console.error(error);
});

API

constructor(fns = [], args = [], errors = [])

  • fns: Array of functions to be executed in sequence.
  • args: Initial arguments stored as args in instance and available as context.args.
  • errors: An array to store any errors that occur during the execution of the functions.

Properties

  • lastResult: Stores the result of the last executed function.
  • errors: Array of errors caught during the execution of the chain.
  • args: Stores args from constructor

run(timeout)

Executes the chain of functions.

  • timeout: Optional. A number representing the timeout in milliseconds. If the chain does not complete within this time, it is rejected with a timeout error.

Handling Errors

als-smart-promise captures errors thrown in any function in the chain and pushes them to the errors array. The chain continues to execute unless manually stopped using context.reject().

Timeouts

The run method accepts an optional timeout parameter. If the chain of functions does not resolve or reject before the timeout, the promise is rejected with a timeout error.

Example with Timeout

const sp = new SmartPromise([func1, func2]);

sp.run(1000).then(result => {
    console.log(result);
}).catch(error => {
    console.error(error); // 'Promise timeout 1000' if timed out
});