2017-10-01 20 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