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) { module.exports = async function race (p, min = 1, max = p.length) {
min = typeof min === 'number' ? min : 1
max = typeof max === 'number' ? max : p.length
let errors = 0 let errors = 0
const results = [] const results = []
for (let i = 0; i < p.length; i++) {
return new Promise((resolve, reject) => { try {
for (let i = 0; i < p.length; i++) p[i].then(ondone, onerror) const res = await p[i]
function ondone (res) {
if (results.length < max) results.push(res) if (results.length < max) results.push(res)
if (results.length >= max) return resolve(results) if (results.length >= max) return results
if (results.length + errors === p.length) return resolve(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