UNPKG

node-mirai-fgo-gacha

Version:

node-mirai-sdk fgo gacha plugin

35 lines (32 loc) 868 B
/** * @function parallel * @description run parallel jobs * @template T * @template R * @param { T[] } list list * @param { (arg: T) => Promise<R> } fn operating function * @param { number } limit max job num * @returns { Promise<R[]> } */ const parallel = (list, fn, limit = 5) => { const total = list.length; if (total < limit) return Promise.all(list.map(i => fn(i))); return new Promise((resolve, reject) => { const results = [] let current = 0; let completed = 0; const runJob = index => fn(list[index]).then(res => { results[index] = res; completed += 1; if (current >= total) { if (completed >= total) return resolve(results) } else { runJob(current++) } }).catch(reject); for (; current < limit; current++) { runJob(current) } }); }; module.exports = parallel;