Mathias Buus
4 years ago
1 changed files with 9 additions and 16 deletions
@ -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…
Reference in new issue