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) { |
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…
Reference in new issue