Socket
Socket
Sign inDemoInstall

@particle/async-utils

Package Overview
Dependencies
Maintainers
31
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@particle/async-utils

Collection of promise-based async utility functions


Version published
Weekly downloads
330
decreased by-17.09%
Maintainers
31
Weekly downloads
 
Created
Source

@particle/async-utils

Collection of promise-based async utility functions.

Installation

npm install @particle/async-utils --save
const asyncUtils = require('@particle/async-utils');
const {
  delay,
  delayForAtLeast,
  timeout,
  TimeoutError,
  retry,
  retryWithBackoff,
  asyncFilter,
  asyncMap,
  asyncReduceSeries,
  asyncMapSeries,
  execAsPromise,
  upon,
  isPromise
} = asyncUtils;

API

@particle/async-utils


asyncUtils.TimeoutError ⇐ Error

Kind: static class of @particle/async-utils
Extends: Error
Properties

NameTypeDefaultDescription
[msg]string"The operation timed out"The error message

asyncUtils.delay(ms, [value]) ⇒ Promise.<(undefined|Value)>

Create a promise which resolves after a given delay

Kind: static method of @particle/async-utils
Returns: Promise.<(undefined|Value)> - A resolved promise

ParamTypeDescription
msnumberDuration of delay in milliseconds
[value]*Value to resolve the returned promise with (optional)

Example

delay(10).then(() => 'done!');
const value = await delay(10, 'done!');

asyncUtils.delayForAtLeast(ms, promise) ⇒ Promise.<*>

Enforce a minimum delay for any async function

Kind: static method of @particle/async-utils
Returns: Promise.<*> - The result of your async function

ParamTypeDescription
msnumberDuration of delay in milliseconds
promisePromise.<*>Promise generated by your async function

Example

let value;

try {
  value = await delayForAtLeast(200, myFn());
  value // whatever `myFn()` resolved with
} catch (error){
  error // whatever `myFn()` rejected with
}

asyncUtils.timeout(promise, ms, [Err]) ⇒ Promise.<*>

Enforce a timeout for any asnyc function

Kind: static method of @particle/async-utils
Returns: Promise.<*> - The result of your async function or a timeout error rejection

ParamTypeDescription
promisePromise.<*>Promise generated by your async function
msnumberDuration of timeout window in milliseconds
[Err]string | functioncustom error message or type (optional)

Example

let value;

try {
  value = await timeout(myFn(), 1000);
} catch (error){
  error.message; // 'The operation timed out'
  error instanceof asyncUtils.TimeoutError; // true
}

// with a custom error message

try {
  value = await timeout(myFn(), 1000, 'custom message');
} catch (error){
  error.message; // 'custom message'
  error instanceof asyncUtils.TimeoutError; // true
}

// with a custom error constructor

try {
  value = await timeout(myFn(), 1000, MyCustomError);
} catch (error){
  error instanceof MyCustomError; // true
}

asyncUtils.retry(fn, [options]) ⇒ Promise.<*>

Retries a given function an arbitrary number of times optionally delaying retry attempts and / or executing a given function before each retry attempt

Kind: static method of @particle/async-utils
Returns: Promise.<*> - The result of your function

ParamTypeDefaultDescription
fnfunctionThe function you would like to execute and retry upon failure
[options]object
[options.maxAttempts]number1Number of tries to attempt
[options.delayMS]numberDelay before retrying in milliseconds (optional)
[options.beforeRetry]functionFunction to exectute before retrying (optional)

Example

let value;

try {
  value = await retry(myFn, { maxAttempts: 3 });
} catch (error){
  error; // the error thrown by your function on it's last attempt
}

// with a delay

try {
  value = await retry(myFn, { delayMS: 100, maxAttempts: 3 }); // each retry is delayed for 100ms
} catch (error){
  error; // the error thrown by your function on it's last attempt
}

// executing a function before each retry attempt

try {
  value = await retry(myFn, { beforeRetry: cleanUpThing, maxAttempts: 3 }); // cleanUpThing() is called before each retry
} catch (error){
  error; // the error thrown by your function on it's last attempt
}

asyncUtils.retryWithBackoff(fn, [options]) ⇒ Promise.<*>

Retries a given function an arbitrary number of times exponentially delaying retry attempts and optionally executing a given function before each retry attempt

Kind: static method of @particle/async-utils
Returns: Promise.<*> - The result of your function

ParamTypeDefaultDescription
fnfunctionThe function you would like to execute and retry upon failure
[options]object
[options.maxAttempts]number1Number of tries to attempt
[options.factor]number2The exponential factor to use - cannot be less than 1 (optional)
[options.initialDelayMS]number250Base delay in milliseconds from which to calculate retry wait time (optional)
[options.maxDelayMS]numberInfinityMaximum delay in milliseconds to enforce after calculating retry wait time (optional)
[options.beforeRetry]functionFunction to exectute before retrying (optional)

Example

let value;

try {
  value = await retryWithBackoff(myFn, { maxAttempts: 3 });
  // assuming `myFn` resolves on the 3rd and final attempt, call timing is:
  // call 0 - immediately
  // call 1 - 250ms wait
  // call 2 - 1000ms wait
} catch (error){
  error; // the error thrown by your function on it's last attempt
}

// with a customized wait

try {
  value = await retryWithBackoff(myFn, { factor: 3, initialDelayMS: 100, maxAttempts: 4 });
  // assuming `myFn` resolves on the 4th and final attempt, call timing is:
  // call 0 - immediately
  // call 1 - 100ms wait
  // call 2 - 800ms wait
  // call 3 - 2700ms wait
} catch (error){
  error; // the error thrown by your function on it's last attempt
}

// with a maximum delay limit

try {
  value = await retryWithBackoff(myFn, { maxAttempts: 3, maxDelayMS: 500 });
  // assuming `myFn` resolves on the 3rd and final attempt, call timing is:
  // call 0 - immediately
  // call 1 - 250ms wait
  // call 2 - 500ms wait
} catch (error){
  error; // the error thrown by your function on it's last attempt
}

// executing a function before each retry attempt

try {
  value = await retryWithBackoff(myFn, { beforeRetry: cleanUpThing, maxAttempts: 3 }); // cleanUpThing() is called before each retry
} catch (error){
  error; // the error thrown by your function on it's last attempt
}

asyncUtils.asyncFilter(array, filter, [concurrency]) ⇒ Promise.<(array|Error)>

Filters an array using an async callback

Kind: static method of @particle/async-utils
Returns: Promise.<(array|Error)> - Your filtered array or an error

ParamTypeDefaultDescription
arrayarrayThe array to filter
filterfunctionFiltering function applied to each element of the array. Return true to keep the element, false otherwise.
[concurrency]numberInfinityThe max number of concurrent operations to run

Example

let values;

try {
  values = await asyncFilter([1, 2, 3], async (n) => n % 2 === 0);
  values; // [2]
} catch (error){
  error; // the first error thrown by your filter function
}

asyncUtils.asyncMap(array, fn, [concurrency]) ⇒ Promise.<(array|Error)>

Map array values using an async callback

Kind: static method of @particle/async-utils
Returns: Promise.<(array|Error)> - New array with mapped values or an error

ParamTypeDefaultDescription
arrayarrayThe array to filter
fnfunctionFunction that produces an element of the new Array.
[concurrency]numberInfinityThe max number of concurrent operations to run

Example

let values;

try {
  values = await asyncMap([1, 2, 3], async (n) => n + 1);
  values; // [2, 3, 4]
} catch (error){
  error; // the first error thrown by your mapper function
}

asyncUtils.asyncReduceSeries(array, fn, [initial]) ⇒ Promise.<(value|Error)>

Reduce array values using an async callback executed in series

Kind: static method of @particle/async-utils
Returns: Promise.<(value|Error)> - New reduced valued or an error

ParamTypeDescription
arrayarrayThe array to reduce
fnfunctionFunction to execute on each element in the array
[initial]*Value used as the 1st argument to the 1st call of the callback (optional)

Example

let values;

try {
  value = await asyncReduceSeries([1, 2, 3], async (out, n) => out + n, 0);
  value; // 6
} catch (error){
  error; // the first error thrown by your callback function
}

asyncUtils.asyncMapSeries(array, fn) ⇒ Promise.<(array|Error)>

Map array values using an async callback executed in series

Kind: static method of @particle/async-utils
Returns: Promise.<(array|Error)> - New array with mapped values or an error

ParamTypeDescription
arrayarrayThe array to map
fnfunctionFunction that produces an element of the new Array.

Example

let values;

try {
  values = await asyncMapSeries([1, 2, 3], async (n) => n + 1);
  values; // [2, 3, 4]
} catch (error){
  error; // the first error thrown by your mapper function
}

asyncUtils.execAsPromise(fn, ...args) ⇒ Promise.<*>

Execute a given function ensuring that its return value or thrown error is transformed into a promise.

Kind: static method of @particle/async-utils
Returns: Promise.<*> - The result of calling your function as a promise

ParamTypeDescription
fnfunctionFunction to execute.
...args*Arguments to pass to your function.

Example

let values;

try {
  values = await execAsPromise((n) => n + 1, 1, 2, 3);
  values; // [2, 3, 4]
} catch (error){
  error; // the error thrown by your function
}

asyncUtils.upon(promise) ⇒ Promise.<Array.<{error: Error, value: *}>>

Resolve a promise using await without try / catch.

Kind: static method of @particle/async-utils
Returns: Promise.<Array.<{error: Error, value: *}>> - The result of your promise as an array like: [error, value]

ParamTypeDescription
promisePromisePromise to handle

Example

let [error, value] = await upon(myFn());

if (error){
    // handle error
}

console.log(value); // whatever `myFn()` resolved with

asyncUtils.isPromise(x) ⇒ boolean

Determine if input looks like a spec-compliant promsie

Kind: static method of @particle/async-utils
Returns: boolean - Whether or not the given input is a promise

ParamTypeDescription
x*Value to check

Example

if (isPromise(x)){
    // it's a promise!
} else {
    // not a promise!
}

NOTE: Unfortunately, docs have a nasty habit of falling out of date. When in doubt, check usage in tests

FAQs

Package last updated on 12 Aug 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc