0
我想从路由中取出我的CRUD逻辑并将其放入服务层。用承诺编码服务层
所以基本上我想打电话给这样的服务层:
const service = require("../service/post")
router.post("/new", (req, res) => {
service.createPost(req.body.titel, req.body.description, req.body.tags, function(id){
console.log("Created post with id: " + id)
res.redirect("index")
})
})
在我postService.js
文件我有以下功能:
function createPost(titel, description, tags, callback) {
const post = {
titel: titel,
description: description,
tags: tags,
createdAt: new Date(),
deleted: false,
}
console.log("Create Post: " + post.titel + " " + post.description + " " + post.tags + " " + post.createdAt + " " + post.deleted)
knex("posts").insert(post, "id").then(id => {
console.log(id)
callback(id[0])
})
}
目前我使用的是callback
来处理这个功能。
任何建议如何使用更基于承诺的风格来返回id,并且当承诺完成时路由器中的代码将等待?
谢谢你的回复!
我会做额外的一件事,是除了,包装内的尝试。 Node.JS当前会记录一个错误,但将来可能会终止该应用程序。基本上Node.js中的所有端点承诺都需要处理。 – Keith
@Keith错误处理为简洁省略,但是我同意,服务层完全封装了存储错误。 – James