Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@handy-common-utils/promise-utils

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@handy-common-utils/promise-utils

Promise related utilities

  • 1.1.1
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

@handy-common-utils/promise-utils

Promise related utilities

How to use

First add it as a dependency:

npm install @handy-common-utils/promise-utils

Then you can use it in the code:

import { PromiseUtils } from '@handy-common-utils/promise-utils';

async repeatFetchingItemsByPosition<T>(
  fetchItemsByPosition: (parameter: { position?: string }) => Promise<{ position?: string; items?: Array<T> }>,
) {
  return PromiseUtils.repeat(
    fetchItemsByPosition,
    response => response.position ? { position: response.position } : null,
    (collection, response) => response.items ? collection.concat(response.items) : collection,
    [] as Array<T>,
  );
}

You can either import and use the class as shown above, or you can import individual functions directly like below:

import { repeat } from '@handy-common-utils/promise-utils';

API

@handy-common-utils/promise-utils

Globals

@handy-common-utils/promise-utils

Index

Enumerations
Classes
Type aliases
Variables

Type aliases

InParrellelResult

Ƭ InParrellelResult<T>: T extends void ? void : Array<T>

Type parameters:
Name
T

Variables

delayedReject

Const delayedReject: delayedReject = PromiseUtils.delayedReject


delayedResolve

Const delayedResolve: delayedResolve = PromiseUtils.delayedResolve


inParallel

Const inParallel: inParallel = PromiseUtils.inParallel


promiseState

Const promiseState: promiseState = PromiseUtils.promiseState


repeat

Const repeat: repeat = PromiseUtils.repeat


synchronized

Const synchronized: synchronized = PromiseUtils.synchronized


timeoutReject

Const timeoutReject: timeoutReject = PromiseUtils.timeoutReject


timeoutResolve

Const timeoutResolve: timeoutResolve = PromiseUtils.timeoutResolve

Classes

@handy-common-utils/promise-utils

Globals / PromiseUtils

Class: PromiseUtils

Hierarchy
  • PromiseUtils
Index
Methods
Methods
delayedReject

Static delayedReject<T>(ms: number, reason: any): Promise<T>

Create a Promise that rejects after number of milliseconds specified

Type parameters:
NameDefault
Tnever
Parameters:
NameTypeDescription
msnumbernumber of milliseconds after which the created Promise would reject
reasonanythe reason of the rejection for the Promise

Returns: Promise<T>

the new Promise created


delayedResolve

Static delayedResolve<T>(ms: number, result?: T | PromiseLike<T> | undefined): Promise<T>

Create a Promise that resolves after number of milliseconds specified

Type parameters:
Name
T
Parameters:
NameTypeDescription
msnumbernumber of milliseconds after which the created Promise would resolve
result?T | PromiseLike<T> | undefinedthe result to be resolved for the Promise

Returns: Promise<T>

the new Promise created


inParallel

Static inParallel<Data, Result>(parallelism: number, jobs: Iterable<Data>, operation: (job: Data, index: number) => Promise<Result>): Promise<InParrellelResult<Result>>

Run multiple jobs/operations in parallel.

example

 
const topicArns = topics.map(topic => topic.TopicArn!);
await Utils.inParallel(5, topicArns, async topicArn => {
  const topicAttributes = (await sns.getTopicAttributes({ TopicArn: topicArn }).promise()).Attributes!;
  const topicDetails = { ...topicAttributes, subscriptions: [] } as any;
  if (this.shouldInclude(topicArn)) {
    inventory.snsTopicsByArn.set(topicArn, topicDetails);
  }
});

Type parameters:
NameDescription
DataType of the job data, usually it would be an Array
ResultType of the return value of the operation function
Parameters:
NameTypeDescription
parallelismnumberhow many jobs/operations can be running at the same time
jobsIterable<Data>job data which will be the input to operation function. This function is safe when there are infinite unknown number of elements in the job data.
operation(job: Data, index: number) => Promise<Result>the function that turns job data into result asynchronously

Returns: Promise<InParrellelResult<Result>>

Promise of void if the operation function does not return a value, or promise of an arry containing results returned from the operation function.


promiseState

Static promiseState(p: Promise<any>): Promise<PromiseState>

Get the state of the Promise. Please note that the returned value is a Promise, although it resolves immediately.

Parameters:
NameTypeDescription
pPromise<any>the Promise for which we would like to know its state

Returns: Promise<PromiseState>

A Promise that resolves immediately cotaining the state of the input Promise


repeat

Static repeat<Result, Param, Collection>(operation: (parameter: Partial<Param>) => Promise<Result>, nextParameter: (response: Result) => Partial<Param> | null, collect: (collection: Collection, result: Result) => Collection, initialCollection: Collection, initialParameter?: Partial<Param>): Promise<Collection>

Do an operation repeatedly and collect all the results. This function is useful for client side pagination.

example

 
const domainNameObjects = await Utils.repeat(
  pagingParam => apig.getDomainNames({limit: 500, ...pagingParam}).promise(),
  esponse => response.position? {position: response.position} : null,
  (collection, response) => collection.concat(response.items!),
  [] as APIGateway.DomainName[],
);

Type parameters:
NameDescription
Resulttype of the operation result
Paramtype of the input to the operation, normally the input is a paging parameter
Collectiontype of the returned value of this function
Parameters:
NameTypeDefault valueDescription
operation(parameter: Partial<Param>) => Promise<Result>-a function that takes paging parameter as input and outputs a result, normally the operation supports paging
nextParameter(response: Result) => Partial<Param> | null-The function for calculating next parameter from the operation result. Normally the parameter controls paging, This function should return null when next invocation of the operation function is not desired.
collect(collection: Collection, result: Result) => Collection-the function for merging operation result into the collection
initialCollectionCollection-initial collection which would be the first argument passed into the first invocation of the collect function
initialParameterPartial<Param>{}the parameter for the first operation

Returns: Promise<Collection>

Promise of collection of all the results returned by the operation function


synchronized

Static synchronized<T>(lock: any, operation: (previousState: PromiseState | undefined, previousSettledState: PromiseState | undefined, previousResult: any) => Promise<T>): Promise<T>

Equivalent of synchronized in Java. In any situation there's no concurrent execution of any operation function associated with the same lock. The operation function has access to the state (when synchronized is called), settledState (when the operation function is called), and result of the previous operation. In case there is no previous invocation, state, settledState and result would all be undefined.

Type parameters:
Name
T
Parameters:
NameTypeDescription
lockanythe object (could be a string, a number, or this in a class) that is used to apply the lock
operation(previousState: PromiseState | undefined, previousSettledState: PromiseState | undefined, previousResult: any) => Promise<T>function for doing the computation and returning a Promise

Returns: Promise<T>

the result of the operation function


timeoutReject

Static timeoutReject<T>(operation: Promise<T>, ms: number, rejectReason: any): Promise<T>

Apply timeout to an operation, in case timeout happens, reject with the reason specified. If timeout does not happen, the resolved result or rejection reason of the original operation would be returned.

Type parameters:
Name
T
Parameters:
NameTypeDescription
operationPromise<T>the original operation that timeout would be applied
msnumbernumber of milliseconds for the timeout
rejectReasonanythe reason of the rejection in case timeout happens

Returns: Promise<T>

the new Promise that rejects with the specified reason in case timeout happens


timeoutResolve

Static timeoutResolve<T>(operation: Promise<T>, ms: number, result?: T | PromiseLike<T> | undefined): Promise<T>

Apply timeout to an operation, in case timeout happens, resolve to the result specified. If timeout does not happen, the resolved result or rejection reason of the original operation would be returned.

Type parameters:
Name
T
Parameters:
NameTypeDescription
operationPromise<T>the original operation that timeout would be applied
msnumbernumber of milliseconds for the timeout
result?T | PromiseLike<T> | undefinedthe result to be resolved in case timeout happens

Returns: Promise<T>

the new Promise that resolves to the specified result in case timeout happens

Enums

@handy-common-utils/promise-utils

Globals / PromiseState

Enumeration: PromiseState

Index
Enumeration members
Enumeration members
Fulfilled

Fulfilled: = "Fulfilled"


Pending

Pending: = "Pending"


Rejected

Rejected: = "Rejected"

Keywords

FAQs

Package last updated on 02 Jun 2021

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