JS实用工具代码

1、JS控制异步任务并发最大数量限制

提示:

    /***
     * @description 异步任务并发最大数量控制
     * @param {Array<Function>} taskQueue - 异步任务队列数组
     * @param {number} concurrencyLimit - 最大并发任务数量
     * @returns {Promise<void>}
     */
    async function executeAsyncTasks(taskQueue, concurrencyLimit) {
        // 创建一个数组来保存正在执行的任务
        const executing = [];
        // 同时启动最大并发任务数量的任务
        for (let i = 0; i < concurrencyLimit && i < taskQueue.length; i++) {
            const task = taskQueue[i]();
            // 将任务加入到正在执行的数组中
            const executingTask = task.then(() => {
                // 当任务完成后,从正在执行的数组中移除该任务
                executing.splice(executing.indexOf(executingTask), 1);
            });
            executing.push(executingTask);
        }
        // 循环执行剩余的任务
        for (let i = concurrencyLimit; i < taskQueue.length; i++) {
            await Promise.race(executing); // 等待任意一个任务完成
            const task = taskQueue[i](); // 启动下一个任务
            // 将任务加入到正在执行的数组中
            const executingTask = task.then(() => {
                // 当任务完成后,从正在执行的数组中移除该任务
                executing.splice(executing.indexOf(executingTask), 1);
            });
            executing.push(executingTask);
        }
        // 等待所有任务完成
        await Promise.all(executing);
    }

使用示例:

   async function asyncFun(){
        const { data } = await axios({ url: 'http://localhost:3000/test', method: 'POST', });
        return data
    }
    // 创建一个任务数组
    const tasks = [asyncFun, asyncFun, asyncFun , asyncFun,asyncFun, asyncFun];
    // 控制并发执行异步任务
    executeAsyncTasks(tasks, 1); // 最大并发数量为3

2、循环调用接口执行异步任务,直到接口有具体响应结果退出循环调用

interval 即上一次异步任务响应结束后,间隔多久进行下一次任务调用,为0即上一个任务结束立即调用

    /**
     * @description 循环调用接口,直到上一次的接口执行响应结束后,再调用下一个接口
     * @param {Function} apiCall - 调用接口的异步任务函数
     * @param {number} interval - 循环调用的间隔时间(毫秒)
     * @returns {Promise} - 返回一个Promise,当接收到响应结果时resolve,否则reject
     */
    async function callApiUntilResponse(apiCall, interval) {
        let lastResponseTime = 0;
        return new Promise(async (resolve, reject) => {
            while (true) {
                try {
                    const currentTime = Date.now();
                    if (currentTime - lastResponseTime >= interval) {
                        const response = await apiCall();
                        // 如果接收到响应结果,则resolve , 需要根据实际结束条件进行修改,此处只做演示
                        if (response) {
                            resolve(response); 
                            break;
                        }
                        lastResponseTime = currentTime;
                    }
                } catch (error) {
                    // 如果接口调用失败,则继续循环调用
                    console.error("接口调用失败:", error);
                }
                await new Promise(resolve => setTimeout(resolve, 100)); // 等待间隔时间后再次调用
            }
        });
    }

使用示例:

   async function asyncFun(){
        const { data } = await axios({ url: 'http://localhost:3000/test', method: 'POST', });
        return data
    }
    
    // 调用接口直到接收到响应结果
    callApiUntilResponse(asyncFun, 5000)
        .then(response => console.log("接收到响应结果:", response))
        .catch(error => console.error("发生错误:", error));

3、将时间日期转化成指定格式的字符串,支持时间戳传入

   /***
     * @description 将时间日期转化成指定格式的字符串,支持时间戳
     * @param timeInput 待转化的时间日期字符串,支持时间戳
     * @param formatString 目标字符串格式 , 例如: YYYY年MM月dd日 HH时mm分SS秒
     * @returns {string|*} 格式化后的字符串
     */
    function formatTime(timeInput, formatString) {
        const date = new Date(typeof timeInput === 'number' ? timeInput : Date.parse(timeInput));
        if (isNaN(date.getTime())) {
            return 'Invalid Date';
        }
        const YYYY = date.getFullYear();
        const MM = String(date.getMonth() + 1).padStart(2, '0');
        const DD = String(date.getDate()).padStart(2, '0');
        const HH = String(date.getHours()).padStart(2, '0');
        const mm = String(date.getMinutes()).padStart(2, '0');
        const SS = String(date.getSeconds()).padStart(2, '0');
        const formattedTime = formatString
            .replace('YYYY', YYYY)
            .replace('MM', MM)
            .replace('dd', DD)
            .replace('HH', HH)
            .replace('mm', mm)
            .replace('SS', SS);

        return formattedTime;
    }

使用示例:

    const timestamp = new Date().getTime();
    const inputFormat = 'YYYY年MM月dd日 HH时mm分SS秒';
    console.log(formatTime(timestamp, inputFormat)); // 输出: "2024-09-26 15:30:123"

4、获取本月,上月,近七天,昨天,今天,三个月,六个月的开始结束日期

    function getDateRange(startDate, endDate) {
        return {
            start: startDate,
            end: endDate
        };
    }
    function getLastNDays(n) {
        let today = new Date();
        let startDate = new Date(today);
        startDate.setDate(today.getDate() - n + 1); // +1 to include today
        let endDate = new Date(today);
        return getDateRange(startDate, endDate);
    }
    function getMonthRange(monthOffset) {
        let today = new Date();
        let targetMonth = new Date(today.getFullYear(), today.getMonth() - monthOffset, 1);
        let startDate = new Date(targetMonth);
        let endDate = new Date(today.getFullYear(), today.getMonth() - monthOffset + 1, 0); 
        return getDateRange(startDate, endDate);
    }
    function getDateRangesWithTodayYesterdayAndMonths() {
        let today = new Date();
        return {
            currentMonth: getMonthRange(0),
            lastMonth: getMonthRange(1),
            lastSevenDays: getLastNDays(7),
            yesterday: getLastNDays(1),
            today: getDateRange(new Date(today.getFullYear(), today.getMonth(), today.getDate()), today),
            threeMonthsAgo: getMonthRange(2),
            sixMonthsAgo: getMonthRange(5)
        };
    }

    
    // Usage:
    const dateRangesWithTodayYesterdayAndMonths = getDateRangesWithTodayYesterdayAndMonths();
    
    console.log("昨天开始日期:", dateRangesWithTodayYesterdayAndMonths.yesterday.start);
    console.log("昨天结束日期:", dateRangesWithTodayYesterdayAndMonths.yesterday.end);
    console.log("---------------------------------------------------------------------")
    
    console.log("今天开始日期:", dateRangesWithTodayYesterdayAndMonths.today.start);
    console.log("今天结束日期:", dateRangesWithTodayYesterdayAndMonths.today.end);
    console.log("---------------------------------------------------------------------")
    
    console.log("近七天开始日期:", dateRangesWithTodayYesterdayAndMonths.lastSevenDays.start);
    console.log("近七天结束日期:", dateRangesWithTodayYesterdayAndMonths.lastSevenDays.end);
    console.log("---------------------------------------------------------------------")
    
    console.log("本月开始日期:", dateRangesWithTodayYesterdayAndMonths.currentMonth.start);
    console.log("本月结束日期:", dateRangesWithTodayYesterdayAndMonths.currentMonth.end);
    console.log("---------------------------------------------------------------------")

    console.log("上个月开始日期:", dateRangesWithTodayYesterdayAndMonths.lastMonth.start);
    console.log("上个月结束日期:", dateRangesWithTodayYesterdayAndMonths.lastMonth.end);
    console.log("---------------------------------------------------------------------")

    console.log("三个月前开始日期:", dateRangesWithTodayYesterdayAndMonths.threeMonthsAgo.start);
    console.log("三个月前结束日期:", dateRangesWithTodayYesterdayAndMonths.threeMonthsAgo.end);
    console.log("---------------------------------------------------------------------")

    console.log("六个月前开始日期:", dateRangesWithTodayYesterdayAndMonths.sixMonthsAgo.start);
    console.log("六个月前结束日期:", dateRangesWithTodayYesterdayAndMonths.sixMonthsAgo.end);
  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值