You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript获取前工作日函数prevDate返回undefined问题排查

问题原因分析
  • 递归调用缺失返回语句:当传入的日期减一天后是周六/周日时,你仅执行了prevDate(date)递归调用,但没有将该调用的结果返回,函数该分支执行结束后默认返回undefined,最终外层拿到的就是这个值。
  • 冗余的async关键字:你的函数逻辑全程是同步计算,没有任何异步操作(没有await、IO调用等),加async会强制把返回值包装为Promise,属于完全不必要的写法。
修复方案

最简修复(推荐,移除冗余async)

function prevDate(date) {
    // 可选优化:拷贝原始日期对象,避免修改外部传入的原变量
    const calcDate = new Date(date.getTime())
    calcDate.setDate(calcDate.getDate() - 1)
    if (calcDate.getDay() == 0 || calcDate.getDay() == 6) {
        // 补充return,把递归结果返回上层
        return prevDate(calcDate)
    } else {
        console.log("date: ", calcDate, "day: ", calcDate.getDay())
        return calcDate
    }
}

// 同步函数直接调用即可,不需要用then
const date = new Date("2021-09-20T00:00:00")
const res = prevDate(date)
console.log("res: ", res)

保留async的修复方案

如果业务场景强制要求函数返回Promise,可按以下方式修改:

async function prevDate(date) {
    date.setDate(date.getDate()-1)
    if (date.getDay() == 0 || date.getDay() == 6) {
        // 补充return,把递归返回的Promise透传到外层
        return prevDate(date)
    } else {
        console.log("date: ", date, "day: ", date.getDay())
        return date
    }
}

// 调用逻辑保持不变
const date = new Date("2021-09-20T00:00:00")
prevDate(date)
.then((res) => {
    console.log("res: ", res)
})
.catch((err) => {
    console.log(err)
})

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:57:03