我尝试在 Node API Controller 中使用异步函数,但从我的“错误处理程序”中间件收到错误。
TypeError: fn is not a function at eval (webpack:///./app/middleware/errorHandler.js?:16:21)
它不像我的 Controller 导出的“findAll”函数,为什么这不是一个函数?我正确导出该函数吗?我是否正确使用了 async/await ?我需要为此使用 Polyfill 吗?我了解到 Node v8 支持 async/await。我目前运行的是 Node v11.10 和 Express v4.16.4。
这是我的路线文件:
// routes.js
const verifyToken = require('../../middleware/verifyToken.js');
const errorHandler = require('../../middleware/errorHandler.js');
module.exports = app => {
const controller = require('../../controllers/controller.js');
app.get(`/collection`, verifyToken, errorHandler(controller.findAll));
}
这是我的 Controller :
// controller.js
exports.findAll = async (req, res) => {
const collections = await collection.find().populate('other');
res.send(collections);
};
这是我的中间件:
// errorHandler.js
module.exports = fn => {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
};
非常感谢任何帮助。
最佳答案
我不确定,但 errorHandler 是否期望 fn 是错误?如果是的话,为什么叫passing(req, res next)?
我使用以下结构:
路由器
// routes.js
const verifyToken = require('../../middleware/verifyToken.js');
const controller = require('../../controllers/controller.js');
var router = express.Router()
router.route('/collection').get(
verifyToken,
controller.findAll
)
module.exports = router
Controller
// controller.js
const asyncUtil = fn =>
function asyncUtilWrap(req, res, next, ...args) {
const fnReturn = fn(req, res, next, ...args)
return Promise.resolve(fnReturn).catch(next)
}
module.exports = {
findAll: asyncUtil(async (req, res, next) => {
const collections = await collection.find().populate('other'); // you can do try/catch here if you want to handle the error here
res.send(collections);
};
然后错误处理程序通常位于 app.js 的底部(但您可以将其放置在路由器的底部):
// app.js
app.use(function(err, req, res, next) {
res.status(err.status || 500)
res.send(err.message)
})
关于javascript - Node JS 异步/等待 Controller 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54892345/