mileOfSunshine / blog

2 stars 0 forks source link

Functions #44

Open mileOfSunshine opened 2 months ago

mileOfSunshine commented 2 months ago

获取指定时间段的所有日期

function getDatesInRange(startDateStr, endDateStr, format = 'YYYY-MM-DD') {
    const startDate = new Date(startDateStr);
    const endDate = new Date(endDateStr);

    let currentDate = new Date(startDate);
    const dates = [];

    while (currentDate <= endDate) {
        dates.push(currentDate.toISOString().split('T')[0]); // 使用ISO日期格式,然后分割出日期部分
        currentDate.setDate(currentDate.getDate() + 1); // 移至下一天
    }

    // 如果需要特定的日期格式,可以在这里进行格式化
    if (format !== 'YYYY-MM-DD') {
        return dates.map(date => {
            const formattedDate = new Date(date);
            return formattedDate.toLocaleDateString(undefined, {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit'
            }).replace(/\//g, '-'); // 替换掉默认格式中的斜杠为短横线
        });
    }

    return dates;
}

// 使用示例
const startDate = '2023-01-01';
const endDate = '2023-01-10';
const allDates = getDatesInRange(startDate, endDate);
console.log(allDates); // 输出从2023-01-01到2023-01-10的所有日期
mileOfSunshine commented 1 month ago

实现一个请求,10s内可重试3次,3次都失败则抛出错误

function request() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            reject()
        }, 3000)
    })
}

function fn(retryCount = 3) {
    return new Promise((resolve, reject) => {
        function retry() {
            // 判断请求超{retryCount}次
            if (retryCount > 0) {
                retryCount--
                return request().then(() => {
                }).catch(e => {
                    retry()
                })
            } else {
                return reject('已请求3次')
            }
        }
        retry()
    })
}

// 计时器
function timer() {
    // 设置超时时间为10秒
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            return reject('请求超时')
        }, 10000)
    })
}

// 计时器和请求重试,看哪个先到达
Promise.race([fn(), timer()]).then(res => {
    console.log('res=>>', res)
}).catch(e => {
    console.error('e==>', e)
})