do-times
Version:
Call an async function `n` times and await the promise returned by it
48 lines (39 loc) • 1.05 kB
Markdown
Call an async function `n` times and await the promise returned by it.
```bash
npm install do-times
```
On engines that do not support `async/await`, use version `2.x.x`:
```bash
npm install do-times@2
```
```javascript
import doTimes from 'do-times'
// const doTimes = require('do-times')
doTimes(3, async (t, i) => new Promise(resolve => {
setTimeout(() => {
console.log({t, i})
resolve(`time_${t}`)
}, 1000)
}))
.then(values => console.log(values))
//=> {t: 1, i: 0}
//=> {t: 2, i: 1}
//=> {t: 3, i: 2}
//=> ['time_1', 'time_2', 'time_3']
// Sync equivalent
doTimes(3, (t, i) => {
console.log({t, i})
return `time_${t}`
})
.then(values => console.log(values))
//=> {t: 1, i: 0}
//=> {t: 2, i: 1}
//=> {t: 3, i: 2}
//=> ['time_1', 'time_2', 'time_3']
```
The package is ~2kB unpacked, has no dependencies, includes a JSDoc reference, and is compatible with browsers that has support for `async/await`, `arrow functions` and `const/let`, and with node `>=7.6.0`.
MIT