UNPKG

@ghini/kit

Version:

js practical tools to assist efficient development

40 lines (39 loc) 1.34 kB
export { queue }; function queue(num = 1, options = {}) { if (typeof num !== "number" || num < 1) { throw new TypeError("并发数(num)必须是一个大于等于1的数字。"); } const { minInterval = 0 } = options; const taskQueue = []; const availableWorkerIds = Array.from({ length: num }, (_, i) => i); let nextAvailableSlotTime = Date.now(); function next() { if (availableWorkerIds.length === 0 || taskQueue.length === 0) return; const workerId = availableWorkerIds.shift(); const taskItem = taskQueue.shift(); const now = Date.now(); const scheduledTime = Math.max(now, nextAvailableSlotTime); const delay = scheduledTime - now; nextAvailableSlotTime = scheduledTime + minInterval; setTimeout(async () => { const { task, resolve, reject } = taskItem; try { resolve(await task(workerId)); } catch (error) { reject(error); } finally { availableWorkerIds.push(workerId); next(); } }, delay); } return (task) => { return new Promise((resolve, reject) => { taskQueue.push({ task, resolve, reject }); next(); }); }; }