async-counter
Advanced tools
Comparing version
@@ -5,6 +5,6 @@ function asyncCounter(max, { | ||
} = {}) { | ||
const counter = {}; | ||
counter.finished = new Promise(resolve => { | ||
let count; | ||
const counter = new Promise(resolve => { | ||
let current = 0; | ||
counter.count = payload => { | ||
count = payload => { | ||
if (++current >= max) { | ||
@@ -18,3 +18,4 @@ resolve(max); | ||
}); | ||
counter.finished.then(onFinished); | ||
counter.count = count; | ||
counter.then(onFinished); | ||
return counter; | ||
@@ -21,0 +22,0 @@ } |
{ | ||
"name": "async-counter", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"description": "An asynchronous counter for Node.js and the browser", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -6,3 +6,3 @@ [](https://www.npmjs.com/package/async-counter) | ||
An asynchronous counter for Node.js and the browser | ||
An asynchronous counter with a sync interface | ||
@@ -23,6 +23,3 @@ ### Install | ||
// Inside an async block | ||
const logWhenFinished = async () => { | ||
await counter.finished; | ||
console.log('finished counting'); | ||
}; | ||
const logWhenFinished = async () => console.log(`Finished counting to ${await counter}!`); | ||
@@ -32,3 +29,7 @@ // Somewhere else, async code | ||
setTimeout(() => counter.count(), 1000); | ||
// `counter.finished` resolves the second time `count` is called | ||
// `counter` resolves the second time `counter.count` is called | ||
logWhenFinished(); | ||
// Output after a second: | ||
// Finished counting to 2! | ||
``` | ||
@@ -39,10 +40,15 @@ | ||
```js | ||
let countTimes = 3; | ||
const counter = asyncCounter(countTimes, { | ||
const counter = asyncCounter(3, { | ||
onFinished: max => console.log(`Finished counting to ${max}!`), | ||
onCount: ({payload, max, current}) => console.log(`${payload.date.toString()}: ${current} of ${max} times`) | ||
}); | ||
for (; countTimes > 0; countTimes--) { | ||
setTimeout(() => counter.count({date: new Date()}), countTimes * 1000); | ||
for (let i = 0; i < 3; i++) { | ||
setTimeout(() => counter.count({date: new Date()}), i * 1000); | ||
} | ||
// Output: | ||
// Wed Feb 27 2019 04:40:05 GMT-0500 (Eastern Standard Time): 1 of 3 times | ||
// Wed Feb 27 2019 04:40:06 GMT-0500 (Eastern Standard Time): 2 of 3 times | ||
// Wed Feb 27 2019 04:40:07 GMT-0500 (Eastern Standard Time): 3 of 3 times | ||
// Finished counting to 3! | ||
``` | ||
@@ -49,0 +55,0 @@ |
4016
6.98%23
4.55%54
12.5%