Files
juzi/h5/lib/provider-gate.js
T

18 lines
704 B
JavaScript

'use strict';
// Rednote-only admission control. Includes JSON consumption in the critical section.
module.exports = function providerGate(fetchImpl, maxPending = 4) {
let tail = Promise.resolve(), pending = 0;
return function (...args) {
if (pending >= maxPending) return Promise.reject(Error('Detection queue is full'));
pending++;
const result = tail.then(async () => {
args[1]?.signal?.throwIfAborted();
const response = await fetchImpl(...args);
const data = await response.json();
return { ok: response.ok, status: response.status, json: async () => data };
});
tail = result.catch(() => {}).finally(() => { pending--; });
return result;
};
};