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

将健身计划接口代码改写为async/await格式并调整输出结构

解决方案

核心实现思路:

  • 用async/await替代嵌套Promise调用,去掉冗余的手动Promise封装
  • 按天维度生成并行查询任务,将每天的查询结果合并后直接组装为目标对象结构,不需要后续额外做数据格式转换

第一步:补全类型定义(可选但推荐,替换原代码冗余的any类型)

// 可根据实际业务调整字段类型
type Plan = Record<string, Record<string, number[]>>
type Exercise = Record<string, any>

第二步:改写getExercises函数

const getExercises = async (plan: Plan): Promise<Record<string, Exercise[]>> => {
  const result: Record<string, Exercise[]> = {}
  // 遍历计划中的每一天
  for (const day in plan) {
    const muscleGroups = plan[day]
    // 收集当天所有肌肉组的查询请求
    const dayQueryTasks = Object.entries(muscleGroups).map(async ([muscle, exerciseIds]) => {
      const query = format("select * from %I where id in (%L)", muscle, exerciseIds)
      try {
        const queryRes = await pool.query(query)
        if (!queryRes?.rows) throw new Error(`查询${muscle}动作数据失败`)
        return queryRes.rows
      } catch (err) {
        console.error(err)
        throw new Error("计划数据不存在")
      }
    })
    // 等待当天所有查询完成,合并多肌肉组的返回结果为一维数组
    const dayExerciseList = await Promise.all(dayQueryTasks)
    result[day] = dayExerciseList.flat()
  }
  return result
}

第三步:改写路由接口

router.get("/workout-plan/:plan", async (req: any, res: any) => {
  try {
    const planName = req.params.plan.toLowerCase()
    const targetPlan = getPlan(planName)
    if (!targetPlan) return res.json({ error: `无${planName}对应的训练计划` })
    const finalPlan = await getExercises(targetPlan)
    res.json(finalPlan)
  } catch (err: any) {
    res.json({ error: err.message })
  }
})

原有计划定义部分可保持不变

const PPL: Plan = {
  d1: {
    chest: [1, 2, 3],
    triceps: [1, 2, 3],
  },
  d2: {
    back: [1, 2, 3],
    biceps: [1, 2, 3],
  },
};

export const plans: { [name: string]: Plan } = {
  ppl: PPL,
};

如果需要保留肌肉组维度的分组,去掉flat()方法,调整结果组装逻辑即可得到{d1: {chest: [], triceps: []}, d2: {}}的分层结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:09:03