async-counter
Advanced tools
Comparing version 0.0.2 to 0.0.4
35
index.js
class AsyncCounter { | ||
constructor(countTimes) { | ||
let currentCount = 0; | ||
this.countTimes = countTimes; | ||
this.ready = new Promise(resolveReady => { | ||
this.finished = new Promise(resolveFinished => { | ||
const count = () => { | ||
currentCount++; | ||
if (currentCount >= this.countTimes) { | ||
resolveFinished(); | ||
} | ||
return currentCount; | ||
}; | ||
this.count = () => this.ready.then(() => count()); | ||
resolveReady(); | ||
}); | ||
constructor(max, onCount = ({payload, max, current}) => {}) { | ||
this.max = max; | ||
this.finished = new Promise(resolve => { | ||
let current = 0; | ||
this.count = (payload = null) => { | ||
if (++current >= this.max) { | ||
resolve(); | ||
} | ||
onCount({payload, current, max: this.max}); | ||
return current; | ||
}; | ||
}); | ||
@@ -21,5 +17,8 @@ } | ||
module.exports = { | ||
const asyncCounter = (max, onCount = ({payload, max, current}) => {}) => new AsyncCounter(max, onCount); | ||
module.exports = Object.assign(asyncCounter, { | ||
AsyncCounter, | ||
asyncCounter: countTimes => new AsyncCounter(countTimes) | ||
}; | ||
asyncCounter, | ||
default: asyncCounter | ||
}); |
{ | ||
"name": "async-counter", | ||
"version": "0.0.2", | ||
"version": "0.0.4", | ||
"description": "An asynchronous counter for Node.js and the browser", | ||
@@ -41,6 +41,6 @@ "main": "index.js", | ||
"rules": { | ||
"promise/param-names": 0, | ||
"promise/prefer-await-to-then": 0 | ||
"promise/prefer-await-to-then": 0, | ||
"no-unused-vars": 0 | ||
} | ||
} | ||
} |
@@ -17,7 +17,11 @@ [![npm version](https://badge.fury.io/js/async-counter.svg)](https://www.npmjs.com/package/async-counter) | ||
```js | ||
import asyncCounter from 'async-counter'; | ||
const counter = asyncCounter(2); | ||
// Inside an async block | ||
await counter.finished; | ||
console.log('finished counting'); | ||
const logWhenFinished = async () => { | ||
await counter.finished; | ||
console.log('finished counting'); | ||
}; | ||
@@ -27,4 +31,3 @@ // Somewhere else, async code | ||
setTimeout(() => counter.count(), 1000); | ||
// counter.finished resolves the second time it is called | ||
// `counter.finished` resolves the second time `count` is called | ||
``` | ||
@@ -31,0 +34,0 @@ |
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
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
3533
35
21