在我的主路由文件中,我需要多次调用一段代码,所以我试图将这段代码放在一个名为“getDayWorkout”的单独模块中,这样我就不必一遍又一遍地重复。我正在努力实现这一目标。现在,getDayWorkout 函数被触发,但它没有到达其中的嵌套函数。下面是我的主路由文件中的代码,然后是导出为“getDayWorkout”的外部模块上的代码。任何帮助表示赞赏。
const express = require('express')
const router = express.Router()
const connection = require('../../helpers/connection')
const getDayWorkout = require('../middlewares/getDayWorkout') // <= external module
router.get("/fetchcustomworkoutplan/:id", (req, res) => {
console.log('MENFIS39: ', req.params)
const userId = parseInt(req.params.id);
let queryString = "SELECT day_one, day_two, day_three, day_four, day_five, day_six, day_seven FROM user_workout_plans WHERE user_id = ? AND status = ?"
connection.query(queryString, [userId, 'Active'], async (err, rows, fields) => {
if (err) {
// // console.log(err)
res.status(500).json({error: 'error'})
return
}
if (rows.length === 0) {
res.json(rows)
return
}
console.log('wokour opans: ', rows)
const userWorkoutPlans = rows[0]
const { day_one, day_two, day_three, day_four, day_five, day_six, day_seven } = userWorkoutPlans
if (day_one !== null) {
workoutDayOne = await getDayWorkout(day_one)
}
res.json(res.workoutPlans)
})
})
getDayWorkout 文件:
const connection = require('../../helpers/connection')
function getDayWorkout(dayWorkoutId) {
console.log('here', dayWorkoutId) // <= triggered
return (req, res, next) => {
console.log('here2') // <= triggered
let queryString = "SELECT * FROM workout_sequences WHERE workout_id = ?"
connection.query(queryString, [dayWorkoutId], (err, rows, fields) => {
if (err) {
// // console.log(err)
res.status(500).json({error: 'error'})
return
}
console.log('hit')
return rows
})
}
}
module.exports = getDayWorkout;
答案 0 :(得分:1)
如果您想从 getDayWorkout
方法返回值,您需要 callback
或 promise
。由于 JS 是异步的,你不能只返回异步调用的值。
这是一个 Promise
的实现,您可以在其中使用 await
或 then
const connection = require('../../helpers/connection')
function getDayWorkout(dayWorkoutId) {
return new Promise((resolve, reject) => {
console.log('here', dayWorkoutId) // <= triggered
console.log('here2') // <= triggered
let queryString = "SELECT * FROM workout_sequences WHERE workout_id = ?"
connection.query(queryString, [dayWorkoutId], (err, rows, fields) => {
if (err) {
reject(err);
return;
}
resolve(rows);
});
});
}
module.exports = getDayWorkout;