本文主要是介绍js async 分批次请求,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题描述:如果merchantNos的数量大于1000需要分批进行请求,如为5000条,则分五次请求,然后把请求的数据拼在一起,如何做到
const merchantNos = ["123","123","123","123","123","123"
]
export const queryOrgInfos = async (params) => {return new Promise((resolve) => {// 模拟异步请求延迟setTimeout(() => {const mockResponse = {code: 0,data: [{"poiName": "123餐厅","merchantNo": "1234","address": "钟楼","brandName": "123品牌",}],};resolve(mockResponse);}, 1000); // 延迟1秒以模拟异步请求});
};
const merchantDetails = await queryOrgInfos(merchantNos);
console.log(merchantDetails, 'merchantDetails')
const queryOrgInfos = async (params) => {return new Promise((resolve) => {// 模拟异步请求延迟setTimeout(() => {const mockResponse = {code: 0,data: [{"poiName": "123","merchantNo": "123","address": "钟楼","brandName": "123",}],};resolve(mockResponse);}, 1000); // 延迟1秒以模拟异步请求});
};
// 定义一个函数,用于分批处理请求,并合并结果
const batchQueryOrgInfos = async (merchantNos, batchSize) => {// 计算需要分多少批const batchCount = Math.ceil(merchantNos.length / batchSize);let allData = [];for (let i = 0; i < batchCount; i++) {// 计算每一批的开始和结束索引const start = i * batchSize;const end = Math.min(start + batchSize, merchantNos.length);// 获取当前批次的merchantNosconst currentBatch = merchantNos.slice(start, end);console.log(currentBatch, 'currentBatch')// 发起请求并获取结果const response = await queryOrgInfos(currentBatch);// 检查响应码是否为0(成功)if (response.code === 0) {// 将当前批次的数据添加到总数据中allData = allData.concat(response.data);} else {// 可以根据实际需求处理错误情况console.error('Error fetching data for batch:', i, 'Response:', response);}}return {code: 0,data: allData};
};// 假设我们有5000个merchantNos
const merchantNos = ["51550082","51550083","51550084","51550085","51550086"
]; // 5000个merchantNo的数组// 定义每批请求的大小
const batchSize = 3;// 使用分批处理函数获取所有的商户详情
const merchantDetails = await batchQueryOrgInfos(merchantNos, batchSize);
console.log(merchantDetails, 'merchantDetails');
这篇关于js async 分批次请求的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!