2017-10-01 21 views
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,并且当承诺完成时路由器中的代码将等待?

谢谢你的回复!

回答

2

在你的榜样,你可以摆脱你的callback参数和返回由knex

createPost(...) { 
    ... 
    return knex('posts').insert(post, "id"); 
} 

返回的承诺,然后在你的路线,你可以,如果你await结果

router.post('/new', async (req, res) => { 
    const id = await service.createPost(...); 
    console.log("Created post with id: " + id[0]); 
    res.redirect("index"); 
}); 

另外,想要预处理来自knex的响应(因为它返回一个数组),那么你可以返回一个新的Promise

async createPost(...) { 
    ... 
    const result = await knex('posts').insert(...); 
    return result[0]; 
} 

FWIW我建议后者,因为它提供了层之间的干净分离。

+0

我会做额外的一件事,是除了,包装内的尝试。 Node.JS当前会记录一个错误,但将来可能会终止该应用程序。基本上Node.js中的所有端点承诺都需要处理。 – Keith

+0

@Keith错误处理为简洁省略,但是我同意,服务层完全封装了存储错误。 – James