第十二篇 手写原理代码

您所在的位置:网站首页 js控制并发数 第十二篇 手写原理代码

第十二篇 手写原理代码

2023-04-13 02:05| 来源: 网络整理| 查看: 265

实现并发控制请求函数 /** * 并发控制请求函数 * @param {Array} urls 请求的 URL 数组 * @param {Number} max 最大并发数 * @param {Function} callback 请求成功回调函数 */ async function concurrentRequest(urls, max, callback) { const len = urls.length; // 用一个数组存储所有的请求结果 const results = new Array(len); // 用一个变量记录已经完成的请求数 let count = 0; // 定义一个请求函数,返回一个 Promise 对象 function request(url) { return new Promise((resolve, reject) => { fetch(url) .then((res) => res.json()) .then((data) => { resolve(data); }) .catch((err) => { reject(err); }); }); } // 利用 while 循环来模拟并发请求过程 while (count < len) { // 判断当前并发数是否已达到最大值,如果未达到则继续发起新的请求 if (count < max) { const index = count; count++; const url = urls[index]; try { // 调用请求函数并保存请求结果 const result = await request(url); results[index] = result; callback && callback(result); } catch (err) { console.error(`Error occurred when fetching ${url}:`, err); } } else { // 如果当前并发数已经达到最大值,就等待其中的一个请求完成后再继续发起新的请求 await Promise.race(results.map((p) => p instanceof Promise && p.catch(() => {}))); } } return results; } 使用 const urls = [ "http://xxa", "http://xxb", "http://xxc", "http://xxd", "http://xxe", "http://xx1e", "http://xx2e", "http://xx3e", "http://x4xe", ] // 定义最大并发数 const maxConcurrent = 3; // 调用 concurrentRequest 函数进行并发控制请求 concurrentRequest(urls, maxConcurrent, (result) => { console.log(result); }).then((results) => { console.log('All requests have been completed:', results); });

原文地址:https://www.cnblogs.com/caix-1987/p/17309377.html



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3