Browse Source

review by @davidmarkclements

session-estimator
Mathias Buus 4 years ago
parent
commit
60bd6c1aa3
  1. 25
      lib/race.js

25
lib/race.js

@ -1,21 +1,14 @@
module.exports = function race (p, min, max) {
min = typeof min === 'number' ? min : 1
max = typeof max === 'number' ? max : p.length
module.exports = async function race (p, min = 1, max = p.length) {
let errors = 0
const results = []
return new Promise((resolve, reject) => {
for (let i = 0; i < p.length; i++) p[i].then(ondone, onerror)
function ondone (res) {
for (let i = 0; i < p.length; i++) {
try {
const res = await p[i]
if (results.length < max) results.push(res)
if (results.length >= max) return resolve(results)
if (results.length + errors === p.length) return resolve(results)
if (results.length >= max) return results
if (results.length + errors === p.length) return results
} catch {
if ((p.length - ++errors) < min) throw new Error('Too many requests failed')
}
function onerror () {
if ((p.length - ++errors) < min) reject(new Error('Too many requests failed'))
}
})
}
}

Loading…
Cancel
Save