promise_mtd
Advanced tools
Comparing version 2.2.2 to 3.0.0
@@ -14,4 +14,6 @@ type Unwrap<T> = | ||
export function foreach<Input = any>(data: Array<Input>, handler: (el: Input, index: number) => Promise<void>): void; | ||
export function forEachParallel<Input = any>(data: Array<Input>, params: { pool: number }, handler: (el: Input, index: number) => Promise<void>): void; | ||
export function map<Result = any, Input = any>(data: Array<Input>, handler: (el: Input, index: number) => Promise<Result>): Promise<Array<Result>>; | ||
export function mapParallel<Result = any, Input = any>(data: Array<Input>, params: { pool: number }, handler: (el: Input, index: number) => Promise<Result>): Promise<Array<Result>>; | ||
@@ -21,20 +23,21 @@ export function reduce<Result = any, Input = any>(data: Array<Input>, handler: (previousValue: Input, currentValue: Input, index: number, array: Array<Input>) => Promise<Input>, initialValue: Input): Promise<Input>; | ||
export function transform<Result = any, Input = any>(data: Array<Input>, handler: (el: Input, index: number) => Promise<Result> | null | undefined): Promise<Array<Result>>; | ||
export function transformParallel<Result = any, Input = any>(data: Array<Input>, params: { pool: number }, handler: (el: Input, index: number) => Promise<Result> | null | undefined): Promise<Array<Result>>; | ||
export function filter<Input = any>(data: Array<Input>, handler: (el: Input, index: number) => Promise<boolean>): Promise<Array<Input>>; | ||
export function filterParallel<Input = any>(data: Array<Input>, params: { pool: number }, handler: (el: Input, index: number) => Promise<boolean>): Promise<Array<Input>>; | ||
export function find<Input = any>(data: Array<Input>, handler: (el: Input, index: number) => Promise<boolean>): Promise<Input>; | ||
export function findParallel<Input = any>(data: Array<Input>, params: { pool: number }, handler: (el: Input, index: number) => Promise<boolean>): Promise<Input>; | ||
export function async_while(check: () => boolean, handler: () => void, params?: { limit: number }): Promise<null>; | ||
export function asyncWhile(check: () => boolean, handler: () => void, params?: { limit: number }): Promise<null>; | ||
export function while_(check: () => boolean, handler: () => void, params?: { limit: number }): Promise<null>; | ||
export function while_(handler: () => Promise<boolean>, params?: { limit: number }): Promise<null>; | ||
export function async_while(handler: () => Promise<boolean>, params?: { limit: number }): Promise<null>; | ||
export function asyncWhile(handler: () => Promise<boolean>, params?: { limit: number }): Promise<null>; | ||
export function retry<T extends (...args: any) => any, E extends { new(...arg: any): any }>(fn: T, settings: { attemp: number, delay?: { ms: number }, ifError?: E }): (...argv: Parameters<T>) => Promise<ReturnType<T>>; | ||
export function parallel<Input = any>(data: Array<Input>, params: { pool: number } | number, handler: (el: Input, index: number) => Promise<void>): void; | ||
export function all<T>(list: T): Promise<UnwrapListOrObject<T>>; | ||
export function all<T extends Object>(list: T): Promise<UnwrapListOrObject<T>>; | ||
export function timeout(ms: number): void; | ||
export function setImmediate(): Promise<null>; | ||
} | ||
27
index.js
@@ -5,20 +5,27 @@ 'use strict'; | ||
promise_mtd.foreach = promise_mtd.forEach = require('./src/foreach.js'); | ||
promise_mtd.foreach = promise_mtd.forEach = require('./src/foreach/foreach.js'); | ||
promise_mtd.forEachParallel = require('./src/foreach/foreach_parallel.js'); | ||
promise_mtd.map = require('./src/map.js'); | ||
promise_mtd.map = require('./src/map/map.js'); | ||
promise_mtd.mapParallel = require('./src/map/map_parallel.js'); | ||
promise_mtd.filter = require('./src/filter.js'); | ||
promise_mtd.filter = require('./src/filter/filter.js'); | ||
promise_mtd.filterParallel = require('./src/filter/filter_parallel.js'); | ||
promise_mtd.find = require('./src/find.js'); | ||
promise_mtd.find = require('./src/find/find.js'); | ||
promise_mtd.findParallel = require('./src/find/find_parallel.js'); | ||
promise_mtd.reduce = require('./src/reduce.js'); | ||
promise_mtd.reduce = require('./src/reduce/reduce.js'); | ||
promise_mtd.transform = require('./src/transform.js'); | ||
promise_mtd.transform = require('./src/transform/transform.js'); | ||
promise_mtd.transformParallel = require('./src/transform/transform_parallel.js'); | ||
promise_mtd.async_while = promise_mtd.asyncWhile = require('./src/async_while.js'); | ||
promise_mtd.while_ = require('./src/while/while.js'); | ||
promise_mtd.parallel = require('./src/parallel.js'); | ||
promise_mtd.all = require('./src/all/all.js'); | ||
promise_mtd.all = require('./src/all.js'); | ||
promise_mtd.retry = require('./src/retry/retry.js'); | ||
promise_mtd.setImmediate = promise_mtd.set_immediate = require('./src/setImmediate.js'); | ||
promise_mtd.setImmediate = promise_mtd.set_immediate = require('./src/setImmediate/setImmediate.js'); | ||
promise_mtd.timeout = require('./src/timeout/timeout.js'); |
@@ -6,3 +6,4 @@ module.exports = { | ||
automock: false, | ||
setupFilesAfterEnv: ['./jest-setup.js'] | ||
setupFilesAfterEnv: ['./jest-setup.js'], | ||
coverageReporters: ['json-summary', 'json-summary', 'text', 'lcov'] | ||
}; |
{ | ||
"name": "promise_mtd", | ||
"version": "2.2.2", | ||
"description": "Set of methods allowing simplify work with Promises in cycle. Methods: forEach, map, find, filter, reduce, while, transform, parallel, all", | ||
"version": "3.0.0", | ||
"description": "Set of methods allowing simplify work with promises in cycle such as: forEach, map, find, filter, reduce, while, transform. Besides there are methods for comfortable work with promises or asynchronous operations - all, retry, timeout.", | ||
"main": "index.js", | ||
@@ -48,2 +48,3 @@ "scripts": { | ||
"rate", | ||
"retry", | ||
"catch", | ||
@@ -66,3 +67,4 @@ "if", | ||
"combinator", | ||
"promise all" | ||
"promise all", | ||
"timeout" | ||
], | ||
@@ -76,4 +78,7 @@ "author": "dm-kamaev@rambler.ru", | ||
"devDependencies": { | ||
"jest": "27.2.0" | ||
"jest": "27.5.1" | ||
}, | ||
"dependencies": { | ||
"coverage-badges": "1.0.5" | ||
} | ||
} |
279
README.md
# promise_mtd | ||
[![Actions Status](https://github.com/dm-kamaev/promise_mtd/workflows/Build/badge.svg)](https://github.com/dm-kamaev/promise_mtd/actions) | ||
[![Actions Status](https://github.com/dm-kamaev/promise_mtd/workflows/Build/badge.svg)](https://github.com/dm-kamaev/promise_mtd/actions) ![Coverage](https://github.com/dm-kamaev/promise_mtd/blob/master/badges/coverage.svg) | ||
Set of methods allowing to simplify work with promises in cycle. The library has support TypeScript. | ||
Set of methods allowing to simplify work with promises in cycle: `forEach, map, find, filter, reduce, while, transform`. Besides there are methods for comfortable work with promises or asynchronous operations: `all, retry, timeout`. | ||
The library supports TypeScript. | ||
* Implementation of ```forEach```, ```map```, ```filter```, ```reduce```, ```find``` for working with array data when it's needed to apply asynchronous function to each element. | ||
* Method ```transform``` allows to iterate asynchronously over an array similarly to ```map```, but also it can skip unnecessary data. | ||
* Implementation of cycle while as ```asyncWhile```(while is reserved word) for using with promise. | ||
* Method ```parallel``` allows to run concurrently promises similarly to method ```Promise.all```, but with limit. | ||
* Method ```all``` allows to run concurrently promises similarly to method ```Promise.all```, but supports receipt of parameter such as object ```{ k1: Promise, k2: Promise }``` not only as array. | ||
Methods: | ||
* `forEach` | ||
* `forEachParallel` | ||
* `map` | ||
* `mapParallel` | ||
* `filter` | ||
* `filterParallel` | ||
* `find` | ||
* `findParallel` | ||
* `reduce` | ||
* `while_` | ||
* `transform` | ||
* `all` | ||
* `retry` | ||
* `timeout` | ||
The library has no dependencies 😀. | ||
The library has no dependencies 😀 | ||
Install: | ||
```sh | ||
npm i promise_mtd -S | ||
``` | ||
How to import: | ||
```js | ||
const promiseMtd = require('promise_mtd'); | ||
import promiseMtd from 'promise_mtd'; | ||
``` | ||
### forEach(Array, function(el, index)) | ||
```forEach``` over promises serially | ||
It's analog of standard method `forEach` of array, but for asynchronous sequent actions based on promises. | ||
```js | ||
const promiseMtd = require('promise_mtd'); | ||
await promiseMtd.forEach([ 300, 200, 100], async function (el, i) { | ||
return new Promise((resolve, reject) => { | ||
setTimeout(function() { | ||
console.log(el); // 300 then 200 then 100 | ||
resolve(); | ||
}, el+i); | ||
}); | ||
await promiseMtd.timeout(el); // inbuilt promifisified version for setTimeout | ||
console.log(el); // 300 then 200 then 100 | ||
}); | ||
``` | ||
### forEachParallel(Array, { pool: number }, function(el, index)) | ||
It's the same method as `forEach`, but actions are executed in parallel. The `pool` is the maximum number of promises executed in parallel. In other words, number of promises which may be executed simutalneously is equal or less than value of `pool`. | ||
```js | ||
await promiseMtd.forEach([ 300, 200, 100], { pool: 2 }, async function (el, i) { | ||
await promiseMtd.timeout(el); // inbuilt promifisified version for setTimeout | ||
console.log(el); // 300 then 200 then 100 | ||
}); | ||
``` | ||
### map(Array<any>, function(el, index): Promise<any>): Promise<Array<any>> | ||
```map``` over promises serially | ||
It's analog of standard method `map` of array, but for asynchronous sequent actions based on promises. | ||
```js | ||
const promiseMtd = require('promise_mtd'); | ||
const result = await promiseMtd.map([ 300, 200, 100 ], async function (el, i) { | ||
await promiseMtd.timeout(el); // inbuilt promifisified version for setTimeout | ||
return el*2; | ||
}); | ||
console.log(result); // [ 600, 400, 200 ] | ||
``` | ||
const result = await promiseMtd.map([ 300, 200, 100], async function (el, i) { | ||
return new Promise((resolve, reject) => { | ||
setTimeout(function() { | ||
resolve(el*2); | ||
}, el*2); | ||
}); | ||
### mapParallel(Array<any>, { pool: number }, function(el, index): Promise<any>): Promise<Array<any>> | ||
It's the same method as `map`, but actions are executed in parallel. The `pool` is the maximum number of promises executed in parallel. In other words, number of promises which may be executed simutalneously is equal or less than value of `pool`. | ||
```js | ||
const result = await promiseMtd.mapParallel([ 300, 200, 100 ], { pool: 2 }, async function (el, i) { | ||
await promiseMtd.timeout(el); // inbuilt promifisified version for setTimeout | ||
return el*2; | ||
}); | ||
@@ -53,12 +79,7 @@ console.log(result); // [ 600, 400, 200 ] | ||
### reduce(Array, function(previousValue, currentValue, index, array): Promise) | ||
```reduce``` over promises serially | ||
It's analog of standard method `reduce` of array, but for asynchronous sequent actions based on promises. | ||
```js | ||
const promiseMtd = require('promise_mtd'); | ||
const result = await promiseMtd.reduce([0, 1, 2, 3, 4], function (previousValue, currentValue, index, array) { | ||
return new Promise((resolve) => { | ||
setTimeout(() => { | ||
resolve(previousValue + currentValue); | ||
}, currentValue*1000); | ||
}); | ||
const result = await promiseMtd.reduce([0, 1, 2, 3, 4], async function (previousValue, currentValue, index, array) { | ||
await promiseMtd.timeout(currentValue * 1000); // inbuilt promifisified version for setTimeout | ||
return previousValue + currentValue; | ||
}, 0); | ||
@@ -70,12 +91,17 @@ console.log(result); // 10 | ||
### filter(Array<any>, function(el, index): Promise<Boolean>): Array<any> | ||
```filter``` over promises serially | ||
It's analog of standard method `filter` of array, but for asynchronous sequent actions based on promises. | ||
```js | ||
const promiseMtd = require('promise_mtd'); | ||
const result = await promiseMtd.filter([ 1, 2, 3, 4 ], async function(el, i) { | ||
await promiseMtd.timeout(el * 1000); // inbuilt promifisified version for setTimeout | ||
return i % 2 === 0; | ||
}); | ||
console.log(result); // [ 2, 4 ] | ||
``` | ||
const result = await promiseMtd.filter([ 1, 2, 3, 4 ], function(time, i) { | ||
return new Promise((resolve, reject) => { | ||
setTimeout(function() { | ||
resolve(i % 2 === 0); | ||
}, time * 1000); | ||
}); | ||
### filterParallel(Array, { pool: number }, function(el, index): Promise<Boolean>): Array<any> | ||
It's the same method as `filter`, but actions are executed in parallel. The `pool` is the maximum number of promises executed in parallel. In other words, number of promises which may be executed simutalneously is equal or less than value of `pool`. | ||
```js | ||
const result = await promiseMtd.filterParallel([ 1, 2, 3, 4 ], { pool: 2 }, async function(el, i) { | ||
await promiseMtd.timeout(el * 1000); // inbuilt promifisified version for setTimeout | ||
return i % 2 === 0; | ||
}); | ||
@@ -85,13 +111,8 @@ console.log(result); // [ 2, 4 ] | ||
### find(Array, function(el, index): Promise) | ||
```find``` over promises serially | ||
### find(Array, function(el, index): Promise): any | ||
It's analog of standard method `find` of array, but for asynchronous sequent actions based on promises. | ||
```js | ||
const promiseMtd = require('promise_mtd'); | ||
const result = await promiseMtd.find([0, 1, 2, 3, 4], function (previousValue, currentValue, index, array) { | ||
return new Promise((resolve) => { | ||
setTimeout(() => { | ||
resolve(el === 2); | ||
}, el*1000); | ||
}); | ||
const result = await promiseMtd.find([0, 1, 2, 3, 4], async function (el, i) { | ||
await promiseMtd.timeout(el * 1000); // inbuilt promifisified version for setTimeout | ||
return el === 2; | ||
}); | ||
@@ -101,29 +122,32 @@ console.log(result); // 2 | ||
### parallel(Array<any>, { pool: number }, function(el, index)) | ||
Equivalent of ```Promise.all``` but with limit | ||
### findParallel(Array, { pool: number }, function(el, index): Promise): any | ||
It's the same method as `find`, but actions are executed in parallel. The `pool` is the maximum number of promises executed in parallel. In other words, number of promises which may be executed simutalneously is equal or less than value of `pool`. | ||
```js | ||
const promiseMtd = require('promise_mtd'); | ||
await promiseMtd.parallel([ 3000, 3000, 3000, 2000, 2000, 2000, 1000], { pool: 3 }, async function(el, i) { | ||
return new Promise((resolve) => { | ||
setTimeout(() => { | ||
console.log(el); | ||
resolve(); | ||
}, t); | ||
}); | ||
const result = await promiseMtd.findParallel([0, 1, 2, 3, 4], { pool: 2 }, async function (el, i) { | ||
await promiseMtd.timeout(el * 1000); // inbuilt promifisified version for setTimeout | ||
return el === 2; | ||
}); | ||
console.log(result); // 2 | ||
``` | ||
### transform(Array, function(el, index): Promise): Array | ||
Method `transform` allows to iterate asynchronously over an array similarly to `map`, but also it can skip unnecessary data. | ||
```js | ||
const res = await promiseMtd.transform([ 1, 2, 3, 4 ], async function (el, i) { | ||
if (el <= 2) { | ||
await promiseMtd.timeout(i*1000); // inbuilt promifisified version for setTimeout | ||
return { el, i }; | ||
} | ||
}); | ||
console.log(res); // [ { el: 1, i: 0 }, { el: 2, i: 1 } ] | ||
``` | ||
### transform(Array<any>, function(el, index): Promise<any>): Array | ||
Iterating over an array and filter over promises | ||
### transformParallel(Array, { pool: number }, function(el, index): Promise): Array | ||
It's the same method as `transform`, but actions are executed in parallel. The `pool` is the maximum number of promises executed in parallel. In other words, number of promises which may be executed simutalneously is equal or less than value of `pool`. | ||
```js | ||
const promiseMtd = require('promise_mtd'); | ||
const res = await promiseMtd.transform([ 1, 2, 3, 4 ], function (el, i) { | ||
const res = await promiseMtd.transformParallel([ 1, 2, 3, 4 ], { pool: 2 }, async function (el, i) { | ||
if (el <= 2) { | ||
return new Promise((resolve) => { | ||
setTimeout(() => resolve({ el, i }), 1000); | ||
}); | ||
await promiseMtd.timeout(i*1000); // inbuilt promifisified version for setTimeout | ||
return { el, i }; | ||
} | ||
@@ -135,41 +159,33 @@ }); | ||
### while_(condition: () => boolean, function(), params?: { limit: number }) | while_(condition: () => Promise<boolean>, params?: { limit: number }) | ||
Implementation of cycle `while` as `while_` (while is reserved word in JavaScript) for using with promise. | ||
`while_` iterates over promises sequentially. This method supports limit of iterations (protection from forever cycle) via third parameter. | ||
### asyncWhile(condition: () => boolean, function(), params?: { limit: number }) | asyncWhile(condition: () => Promise<boolean>, params?: { limit: number }) | ||
```while``` over promises serially. This method supports limit of iterations (protection from forever cycle) via third parameter& | ||
Example with two arguments: the first argument is function which returns result of condition, the second is asynchronous action. | ||
```js | ||
const promiseMtd = require('promise_mtd'); | ||
let i = 0; | ||
let result = []; | ||
await promiseMtd.asyncWhile(() => i < 10, function () { | ||
return new Promise((resolve) => { | ||
setTimeout(() => { | ||
result.push(i++); | ||
resolve(); | ||
}, i*1000); | ||
}); | ||
await promiseMtd.while_(() => i < 10, async function () { | ||
await promiseMtd.timeout(i*1000); // inbuilt promifisified version for setTimeout | ||
result.push(i++); | ||
}); | ||
console.log(result); // [0,1,2,3,4,5,5,6,7,8,9] | ||
``` | ||
// OR | ||
i = 0 | ||
result = []; | ||
await promiseMtd.asyncWhile(function () { | ||
return new Promise((resolve) => { | ||
setTimeout(() => { | ||
result.push(i++); | ||
resolve(i < 10); | ||
}, i*1000); | ||
}); | ||
Example with one argument, asynchronous function is executed until it returns `false`. | ||
```js | ||
let i = 0 | ||
let result = []; | ||
await promiseMtd.while_(async function () { | ||
await promiseMtd.timeout(i*1000); // inbuilt promifisified version for setTimeout | ||
result.push(i++); | ||
return i < 10; | ||
}); | ||
console.log(result); // [0,1,2,3,4,5,5,6,7,8,9] | ||
// Example: forever cycle, method will throw error | ||
await promiseMtd.asyncWhile(() => true, function () { | ||
return new Promise((resolve) => { | ||
setTimeout(() => { | ||
resolve(); | ||
}, i*1000); | ||
}); | ||
``` | ||
Protection from forever cycle with the help of set `limit`. This code will throw error after 100 iterations. | ||
```js | ||
await promiseMtd.while_(() => true, async function () { | ||
await promiseMtd.timeout(i*1000); // inbuilt promifisified version for setTimeout | ||
}, { limit: 100 }); // protection from forever cycle | ||
@@ -179,18 +195,9 @@ ``` | ||
### all(data: Array<Promise> | Object<{ key: Promise }>): Array<any> | Object<{ key: any }> | ||
```All``` like ```Promise.all``` but it can handle object | ||
### all(data: Array | Object<{ key: Promise }>): Array<any> | Object<{ key: any }> | ||
Method `all` allows to run concurrently promises similarly to method `Promise.all`, but supports receipt of parameter such as object `{ k1: Promise, k2: Promise }` not only as array. | ||
```js | ||
const promiseMtd = require('promise_mtd'); | ||
const t1 = new Promise((resolve, reject) => { | ||
setTimeout(() => { | ||
resolve(2000); | ||
}, 2000); | ||
}); | ||
const t1 = promiseMtd.timeout(2000).then(() => 2000); | ||
const t2 = new Promise((resolve, reject) => { | ||
setTimeout(() => { | ||
resolve(1000); | ||
}, 1000); | ||
}); | ||
const t2 = promiseMtd.timeout(1000).then(() => 1000); | ||
@@ -207,2 +214,46 @@ | ||
### retry(fn: Function, { attempt: number, delay?: { ms: number }, ifError: Error }): Function | ||
This method allows to create wrapper for asynchronous function which repeats calling if the function returns an error. | ||
* `attempt`is parameter which sets number of attempts for executing. | ||
* `delay.ms` is parameter which sets number of milliseconds for delaying between attempts. | ||
* `ifError` is parameter which sets class of errors because of which function must be called repeatedly. In other words, if your function throw error which is not instance of `ifError` then it will throw error immediately. | ||
```js | ||
function req() { | ||
return axios.get('http://example.com/inreliable-path'); | ||
} | ||
const request = promiseMtd.retry(req, { attempt: 3 }); | ||
// throw error after 3 attempts | ||
await request(); | ||
``` | ||
This code throws error after 3 attempts and makes 300 ms delay before every attempt. | ||
```js | ||
const request = promiseMtd.retry(req, { attempt: 3, delay: { ms: 300 } }); | ||
await request(); | ||
``` | ||
This code makes retry if error type instance of `RateLimitError` otherwise throws error immediately. | ||
```js | ||
class RateLimitError extends Error {} | ||
function req() { | ||
return axios.get('http://example.com/auth').then(result => { | ||
if (result === 'rate-limit') { | ||
throw new RateLimitError(); | ||
} | ||
}).then(() => axios.get('http://example.com/inreliable-path')); | ||
} | ||
const request = promiseMtd.retry(req, { attempt: 3, delay: { ms: 300 }, ifError: RateLimitError }); | ||
await request(); | ||
``` | ||
### timeout(ms: number) | ||
It's promifisified version for `setTimeout`. | ||
```js | ||
await promiseMtd.timeout(2000); | ||
``` | ||
## Tests | ||
@@ -209,0 +260,0 @@ ```sh |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
44278
43
1019
255
1
1
+ Addedcoverage-badges@1.0.5
+ Addedcoverage-badges@1.0.5(transitive)