diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..1c6314a --- /dev/null +++ b/.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 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..391f0a4 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +* text=auto +*.js text eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..239ecff --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules +yarn.lock diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..43c97e7 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +package-lock=false diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..b3be97a --- /dev/null +++ b/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - '8' diff --git a/example.js b/example.js new file mode 100644 index 0000000..c7f5aaa --- /dev/null +++ b/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; +})(); diff --git a/index.js b/index.js new file mode 100644 index 0000000..9e235ec --- /dev/null +++ b/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; diff --git a/license b/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (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. diff --git a/package.json b/package.json new file mode 100644 index 0000000..ff70249 --- /dev/null +++ b/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" + } +} diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..03b8e84 --- /dev/null +++ b/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`
+Default: `Infinity`
+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) diff --git a/test.js b/test.js new file mode 100644 index 0000000..7508de3 --- /dev/null +++ b/test.js @@ -0,0 +1,103 @@ +import test from 'ava'; +import delay from 'delay'; +import PProgress from '.'; + +const fixture = Symbol('fixture'); + +test('new PProgress()', async t => { + t.plan(22); + + const p = new PProgress(async (resolve, reject, progress) => { + progress(0.1); + await delay(50); + progress(0.3); + await delay(100); + progress(0.4); + await delay(20); + progress(0.9); + await delay(50); + progress(1); + progress(1); + progress(1); + resolve(fixture); + }); + + t.true(p instanceof Promise); + + p.onProgress(progress => { + t.is(progress, p.progress); + t.true(progress >= 0 && progress <= 1); + }); + + p.onProgress(progress => { + t.is(progress, p.progress); + t.true(progress >= 0 && progress <= 1); + }); + + t.is(await p, fixture); +}); + +test('PProgress.fn()', async t => { + t.plan(4); + + const fn = PProgress.fn(async (input, progress) => { + progress(0.1); + await delay(50); + progress(0.6); + await delay(100); + progress(1); + return input; + }); + + const p = fn(fixture); + + p.onProgress(progress => { + t.true(progress >= 0 && progress <= 1); + }); + + t.is(await p, fixture); +}); + +test('PProgress.all()', async t => { + const fixtureFn = PProgress.fn(async (input, progress) => { + progress(0.16); + await delay(50); + progress(0.55); + await delay(100); + return input; + }); + + const fixtureFn2 = PProgress.fn(async (input, 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); + return input; + }); + + const p = PProgress.all([ + delay(103), + fixtureFn(fixture), + delay(55), + fixtureFn2(fixture), + delay(14), + delay(209) + ]); + + p.onProgress(progress => { + t.true(progress >= 0 && progress <= 1); + }); + + t.deepEqual(await p, [ + undefined, + fixture, + undefined, + fixture, + undefined, + undefined + ]); +});