do-times
Version:
Call an async function `n` times and await the promise returned by it
54 lines (48 loc) • 1.52 kB
JavaScript
/**
* @module do-times
* Call an async function `n` times and await the promise returned by it.
* @async
* @function doTimes
* @param {number} n - The number of times to call the function.
* @param {callback} callback - The function to call `n` times.
* @return {Promise<Array>} - An array of the values returned by the callback function, each time it was called
* @example
* 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']
* @async
* @callback callback
* @param {int} time - The time the function was called
* @param {int} index - Index
* @return {Promise}
*/
const doTimes = async (times, callback) => {
if (typeof times !== 'number') throw 'do-times expected the first argument [times] to be a number'
if (typeof callback !== 'function') throw 'do-times expected the second argument [callback] to be a function'
let values = []
for (let time = 1; time <= times; time++) {
const value = await callback(time, time - 1)
values.push(value)
}
return values
}
module.exports = doTimes