This is not GitHub.com

Like what you see? Install OctoLinker now!

Skip to content
Permalink
Browse files
Require Node.js 12 and move to ESM
  • Loading branch information
sindresorhus committed Apr 17, 2021
1 parent 54b51f9 commit dcdbc7ac1b4384a3b5715495c284f7fa70667e29
Showing with 82 additions and 91 deletions.
  1. +1 −2 .github/workflows/main.yml
  2. +33 −39 index.d.ts
  3. +8 −9 index.js
  4. +11 −12 index.test-d.ts
  5. +11 −9 package.json
  6. +10 −12 readme.md
  7. +8 −8 test.js
@@ -12,10 +12,9 @@ jobs:
node-version:
- 14
- 12
- 10
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- run: npm install
@@ -1,67 +1,61 @@
declare namespace pMap {
interface Options {
/**
Number of concurrently pending promises returned by `mapper`.
Must be an integer from 1 and up or `Infinity`.
@default Infinity
*/
readonly concurrency?: number;
export interface Options {
/**
Number of concurrently pending promises returned by `mapper`.
/**
When set to `false`, instead of stopping when a promise rejects, it will wait for all the promises to settle and then reject with an [aggregated error](https://github.com/sindresorhus/aggregate-error) containing all the errors from the rejected promises.
Must be an integer from 1 and up or `Infinity`.
@default true
*/
readonly stopOnError?: boolean;
}
@default Infinity
*/
readonly concurrency?: number;

/**
Function which is called for every item in `input`. Expected to return a `Promise` or value.
When set to `false`, instead of stopping when a promise rejects, it will wait for all the promises to settle and then reject with an [aggregated error](https://github.com/sindresorhus/aggregate-error) containing all the errors from the rejected promises.
@param element - Iterated element.
@param index - Index of the element in the source array.
@default true
*/
type Mapper<Element = any, NewElement = unknown> = (
element: Element,
index: number
) => NewElement | Promise<NewElement>;
readonly stopOnError?: boolean;
}

/**
Function which is called for every item in `input`. Expected to return a `Promise` or value.
@param element - Iterated element.
@param index - Index of the element in the source array.
*/
export type Mapper<Element = any, NewElement = unknown> = (
element: Element,
index: number
) => NewElement | Promise<NewElement>;

/**
@param input - Iterated over concurrently in the `mapper` function.
@param mapper - Function which is called for every item in `input`. Expected to return a `Promise` or value.
@returns A `Promise` that is fulfilled when all promises in `input` and ones returned from `mapper` are fulfilled, or rejects if any of the promises reject. The fulfilled value is an `Array` of the fulfilled values returned from `mapper` in `input` order.
@example
```
import pMap = require('p-map');
import got = require('got');
import pMap from 'p-map';
import got from 'got';
const sites = [
getWebsiteFromUsername('https://sindresorhus'), //=> Promise
'https://avajs.dev',
'https://github.com'
];
(async () => {
const mapper = async site => {
const {requestUrl} = await got.head(site);
return requestUrl;
};
const mapper = async site => {
const {requestUrl} = await got.head(site);
return requestUrl;
};
const result = await pMap(sites, mapper, {concurrency: 2});
const result = await pMap(sites, mapper, {concurrency: 2});
console.log(result);
//=> ['https://sindresorhus.com/', 'https://avajs.dev/', 'https://github.com/']
})();
console.log(result);
//=> ['https://sindresorhus.com/', 'https://avajs.dev/', 'https://github.com/']
```
*/
declare function pMap<Element, NewElement>(
export default function pMap<Element, NewElement>(
input: Iterable<Element>,
mapper: pMap.Mapper<Element, NewElement>,
options?: pMap.Options
mapper: Mapper<Element, NewElement>,
options?: Options
): Promise<NewElement[]>;

export = pMap;
@@ -1,20 +1,19 @@
'use strict';
const AggregateError = require('aggregate-error');
import AggregateError from 'aggregate-error';

module.exports = async (
export default async function pMap(
iterable,
mapper,
{
concurrency = Infinity,
concurrency = Number.POSITIVE_INFINITY,
stopOnError = true
} = {}
) => {
) {
return new Promise((resolve, reject) => {
if (typeof mapper !== 'function') {
throw new TypeError('Mapper function is required');
}

if (!((Number.isSafeInteger(concurrency) || concurrency === Infinity) && concurrency >= 1)) {
if (!((Number.isSafeInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency >= 1)) {
throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
}

@@ -39,7 +38,7 @@ module.exports = async (
isIterableDone = true;

if (resolvingCount === 0) {
if (!stopOnError && errors.length !== 0) {
if (!stopOnError && errors.length > 0) {
reject(new AggregateError(errors));
} else {
resolve(result);
@@ -70,12 +69,12 @@ module.exports = async (
})();
};

for (let i = 0; i < concurrency; i++) {
for (let index = 0; index < concurrency; index++) {
next();

if (isIterableDone) {
break;
}
}
});
};
}
@@ -1,6 +1,5 @@
import {expectType} from 'tsd';
import pMap = require('.');
import {Options, Mapper} from '.';
import {expectType, expectAssignable} from 'tsd';
import pMap, {Options, Mapper} from './index.js';

const sites = [
'https://sindresorhus.com',
@@ -20,16 +19,16 @@ const asyncSyncMapper = async (site: string, index: number): Promise<string> =>
const multiResultTypeMapper = async (site: string, index: number): Promise<string | number> =>
index > 1 ? site.length : site;

expectType<Mapper>(asyncMapper);
expectType<Mapper<string, string>>(asyncMapper);
expectType<Mapper>(asyncSyncMapper);
expectType<Mapper<string, string | Promise<string>>>(asyncSyncMapper);
expectType<Mapper>(multiResultTypeMapper);
expectType<Mapper<string, string | number>>(multiResultTypeMapper);
expectAssignable<Mapper>(asyncMapper);
expectAssignable<Mapper<string, string>>(asyncMapper);
expectAssignable<Mapper>(asyncSyncMapper);
expectAssignable<Mapper<string, string | Promise<string>>>(asyncSyncMapper);
expectAssignable<Mapper>(multiResultTypeMapper);
expectAssignable<Mapper<string, string | number>>(multiResultTypeMapper);

expectType<Options>({});
expectType<Options>({concurrency: 0});
expectType<Options>({stopOnError: false});
expectAssignable<Options>({});
expectAssignable<Options>({concurrency: 0});
expectAssignable<Options>({stopOnError: false});

expectType<Promise<string[]>>(pMap(sites, asyncMapper));
expectType<Promise<string[]>>(pMap(sites, asyncMapper, {concurrency: 2}));
@@ -10,8 +10,10 @@
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": "./index.js",
"engines": {
"node": ">=10"
"node": ">=12"
},
"scripts": {
"test": "xo && ava && tsd"
@@ -39,15 +41,15 @@
"bluebird"
],
"dependencies": {
"aggregate-error": "^3.0.0"
"aggregate-error": "^4.0.0"
},
"devDependencies": {
"ava": "^2.2.0",
"delay": "^4.1.0",
"in-range": "^2.0.0",
"random-int": "^2.0.0",
"time-span": "^3.1.0",
"tsd": "^0.7.4",
"xo": "^0.27.2"
"ava": "^3.15.0",
"delay": "^5.0.0",
"in-range": "^3.0.0",
"random-int": "^3.0.0",
"time-span": "^5.0.0",
"tsd": "^0.14.0",
"xo": "^0.38.2"
}
}
@@ -15,26 +15,24 @@ $ npm install p-map
## Usage

```js
const pMap = require('p-map');
const got = require('got');
import pMap from 'p-map';
import got from 'got';
const sites = [
getWebsiteFromUsername('https://sindresorhus'), //=> Promise
'https://avajs.dev',
'https://github.com'
];
(async () => {
const mapper = async site => {
const {requestUrl} = await got.head(site);
return requestUrl;
};
const mapper = async site => {
const {requestUrl} = await got.head(site);
return requestUrl;
};
const result = await pMap(sites, mapper, {concurrency: 2});
const result = await pMap(sites, mapper, {concurrency: 2});
console.log(result);
//=> ['https://sindresorhus.com/', 'https://avajs.dev/', 'https://github.com/']
})();
console.log(result);
//=> ['https://sindresorhus.com/', 'https://avajs.dev/', 'https://github.com/']
```

## API
@@ -61,7 +59,7 @@ Type: `object`

##### concurrency

Type: `number` (Integer)\
Type: `number` *(Integer)*\
Default: `Infinity`\
Minimum: `1`

16 test.js
@@ -4,7 +4,7 @@ import inRange from 'in-range';
import timeSpan from 'time-span';
import randomInt from 'random-int';
import AggregateError from 'aggregate-error';
import pMap from '.';
import pMap from './index.js';

const sharedInput = [
Promise.resolve([10, 300]),
@@ -56,7 +56,7 @@ test('concurrency: 4', async t => {
const concurrency = 4;
let running = 0;

await pMap(new Array(100).fill(0), async () => {
await pMap(Array.from({length: 100}).fill(0), async () => {
running++;
t.true(running <= concurrency);
await delay(randomInt(30, 200));
@@ -69,7 +69,7 @@ test('handles empty iterable', async t => {
});

test('async with concurrency: 2 (random time sequence)', async t => {
const input = new Array(10).map(() => randomInt(0, 100));
const input = Array.from({length: 10}).map(() => randomInt(0, 100));
const mapper = value => delay(value, {value});
const result = await pMap(input, mapper, {concurrency: 2});
t.deepEqual(result, input);
@@ -90,16 +90,16 @@ test('async with concurrency: 2 (out of order time sequence)', async t => {
});

test('enforce number in options.concurrency', async t => {
await t.throwsAsync(pMap([], () => {}, {concurrency: 0}), TypeError);
await t.throwsAsync(pMap([], () => {}, {concurrency: 1.5}), TypeError);
await t.throwsAsync(pMap([], () => {}, {concurrency: 0}), {instanceOf: TypeError});
await t.throwsAsync(pMap([], () => {}, {concurrency: 1.5}), {instanceOf: TypeError});
await t.notThrowsAsync(pMap([], () => {}, {concurrency: 1}));
await t.notThrowsAsync(pMap([], () => {}, {concurrency: 10}));
await t.notThrowsAsync(pMap([], () => {}, {concurrency: Infinity}));
await t.notThrowsAsync(pMap([], () => {}, {concurrency: Number.POSITIVE_INFINITY}));
});

test('immediately rejects when stopOnError is true', async t => {
await t.throwsAsync(pMap(errorInput1, mapper, {concurrency: 1}), 'foo');
await t.throwsAsync(pMap(errorInput2, mapper, {concurrency: 1}), 'bar');
await t.throwsAsync(pMap(errorInput1, mapper, {concurrency: 1}), {message: 'foo'});
await t.throwsAsync(pMap(errorInput2, mapper, {concurrency: 1}), {message: 'bar'});
});

test('aggregate errors when stopOnError is false', async t => {

0 comments on commit dcdbc7a

Please sign in to comment.