From 60bd6c1aa36e46b71578db4afd41454ed61faec1 Mon Sep 17 00:00:00 2001 From: Mathias Buus Date: Wed, 2 Jun 2021 17:45:00 +0200 Subject: [PATCH] review by @davidmarkclements --- lib/race.js | 25 +++++++++---------------- 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/lib/race.js b/lib/race.js index bbca109..e586e3c 100644 --- a/lib/race.js +++ b/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')) - } - }) + } }