Skip to content

Commit

Permalink
Init
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Sep 11, 2017
0 parents commit 17a5192
Show file tree
Hide file tree
Showing 11 changed files with 484 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
@@ -0,0 +1,12 @@
root = true

[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.yml]
indent_style = space
indent_size = 2
2 changes: 2 additions & 0 deletions .gitattributes
@@ -0,0 +1,2 @@
* text=auto
*.js text eol=lf
2 changes: 2 additions & 0 deletions .gitignore
@@ -0,0 +1,2 @@
node_modules
yarn.lock
1 change: 1 addition & 0 deletions .npmrc
@@ -0,0 +1 @@
package-lock=false
3 changes: 3 additions & 0 deletions .travis.yml
@@ -0,0 +1,3 @@
language: node_js
node_js:
- '8'
27 changes: 27 additions & 0 deletions example.js
@@ -0,0 +1,27 @@
'use strict';
const delay = require('delay');
const PProgress = require('.');

const progressPromise = PProgress.fn(async progress => {
progress(0.14);
await delay(52);
progress(0.37);
await delay(104);
progress(0.41);
await delay(26);
progress(0.93);
await delay(55);
});

const allProgressPromise = PProgress.all([
delay(103),
progressPromise(),
delay(55),
delay(209)
]);

(async () => {
allProgressPromise.onProgress(console.log);

await allProgressPromise;
})();
112 changes: 112 additions & 0 deletions index.js
@@ -0,0 +1,112 @@
'use strict';
const pMap = require('p-map');

const sum = iterable => {
let total = 0;

for (const value of iterable.values()) {
total += value;
}

return total;
};

class PProgress extends Promise {
static fn(input) {
return (...args) => {
return new PProgress((resolve, reject, progress) => {
args.push(progress);
input(...args).then(resolve, reject);
});
};
}

static all(promises, options) {
return PProgress.fn(progress => {
const progressMap = new Map();
const iterator = promises[Symbol.iterator]();

const reportProgress = () => {
progress(sum(progressMap) / promises.length);
};

const mapper = async () => {
const promise = iterator.next().value;
progressMap.set(promise, 0);

if (promise instanceof PProgress) {
promise.onProgress(percentage => {
progressMap.set(promise, percentage);
reportProgress();
});
}

const value = await promise;
progressMap.set(promise, 1);
reportProgress();
return value;
};

// TODO: This is kinda ugly. Find a better way to do this.
// Maybe `p-map` could accept a number as the first argument?
return pMap(new Array(promises.length), mapper, options);
})();
}

constructor(executor) {
const progressFn = progress => {
if (progress > 1 || progress < 0) {
throw new TypeError('The progress percentage should be a number between 0 and 1');
}

// We run this in the next microtask tick so `super` is called before we use `this`
Promise.resolve().then(() => {
if (progress === this._progress) {
return;
} else if (progress < this._progress) {
throw new Error('The progress percentage can\'t be lower than the last progress event');
}

this._progress = progress;

for (const listener of this._listeners) {
listener(progress);
}
});
};

super((resolve, reject) => {
executor(
value => {
progressFn(1);
resolve(value);
},
reject,
progress => {
if (progress !== 1) {
progressFn(progress);
}
}
);
});

this._listeners = new Set();
this._progressFn = progressFn;
this._progress = 0;
}

get progress() {
return this._progress;
}

onProgress(cb) {
if (typeof cb !== 'function') {
throw new TypeError(`Expected a \`Function\`, got \`${typeof cb}\``);
}

this._listeners.add(cb);
return this;
}
}

module.exports = PProgress;
9 changes: 9 additions & 0 deletions license
@@ -0,0 +1,9 @@
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
40 changes: 40 additions & 0 deletions package.json
@@ -0,0 +1,40 @@
{
"name": "p-progress",
"version": "0.0.0",
"description": "Create a promise that reports progress",
"license": "MIT",
"repository": "sindresorhus/p-progress",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=6"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"promise",
"progress",
"events",
"event",
"async",
"function",
"await",
"promises",
"bluebird"
],
"devDependencies": {
"ava": "*",
"delay": "^2.0.0",
"xo": "*"
},
"dependencies": {
"p-map": "^1.1.1"
}
}
173 changes: 173 additions & 0 deletions readme.md
@@ -0,0 +1,173 @@
# p-progress [![Build Status](https://travis-ci.org/sindresorhus/p-progress.svg?branch=master)](https://travis-ci.org/sindresorhus/p-progress)

> Create a promise that reports progress
Useful for reporting progress to the user during long-running async operations.


## Install

```
$ npm install p-progress
```


## Usage

```js
const PProgress = require('p-progress');

const progressPromise = new PProgress((resolve, reject, progress) => {
const job = new Job();

job.on('data', data => {
progress(data.length / job.totalSize);
});

job.on('finish', resolve);
job.on('error', reject);
});

(async () => {
progressPromise.onProgress(progress => {
console.log(`${progress * 100}%`);
//=> 9%
//=> 23%
//=> 59%
//=> 75%
//=> 100%
});

await progressPromise;
})();
```


## API

### instance = new PProgress(executor)

Same as the [`Promise` constructor](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise), but with an appended `progress` parameter in `executor`.

`PProgress` is a subclass of `Promise`.

###### progress(percentage)

Type: `Function`

Call this with progress updates. It expects a number between 0 and 1.

Multiple calls with the same number will result in only one `onProgress()` event.

Progress percentage `1` is reported for you when the promise resolves. If you set it yourself, it will simply be ignored.

#### instance.progress

Type: `number`

The current progress percentage of the promise as a number between 0 and 1.

#### instance.onProgress(function)

Accepts a function that gets `instance.progress` as an argument and is called for every progress event.

### PProgress.fn(function)

Convenience method to make your promise-returning or async function report progress.

The function you specify will have the `progress()` function appended to its parameters.

```js
const runJob = PProgress.fn(async (name, progress) => {
const job = new Job(name);

job.on('data', data => {
progress(data.length / job.totalSize);
});

await job.run();
});

(async () => {
const progressPromise = runJob('Gather rainbows');

progressPromise.onProgress(console.log);
//=> 0.09
//=> 0.23
//=> 0.59
//=> 0.75
//=> 1

await progressPromise;
})();
```

### PProgress.all(promises, [options])

Convenience method to run multiple promises and get a total progress of all of them. It counts normal promises with progress `0` when pending and progress `1` when resolved. For `PProgress` type promises, it listens to their `onProgress()` method for more fine grained progress reporting. You can mix and match normal promises and `PProgress` promises.

```js
const delay = require('delay');

const progressPromise = PProgress.fn(async progress => {
progress(0.14);
await delay(52);
progress(0.37);
await delay(104);
progress(0.41);
await delay(26);
progress(0.93);
await delay(55);
});

const allProgressPromise = PProgress.all([
delay(103),
progressPromise(),
delay(55),
delay(209)
]);

(async () => {
allProgressPromise.onProgress(console.log);
//=> 0.0925
//=> 0.3425
//=> 0.5925
//=> 0.6025
//=> 0.7325
//=> 0.9825
//=> 1

await allProgressPromise;
})();
```

#### promises

Type: `Array`

Array of promises.

#### options

Type: `Object`

##### concurrency

Type: `number`<br>
Default: `Infinity`<br>
Minimum: `1`

Number of concurrently pending promises.

To run the promises in series, set it to `1`.


## Related

- [p-cancelable](https://github.com/sindresorhus/p-cancelable) - Create a promise that can be canceled
- [More…](https://github.com/sindresorhus/promise-fun)


## License

MIT © [Sindre Sorhus](https://sindresorhus.com)

0 comments on commit 17a5192

Please sign in to comment.