我是新來承諾並試圖在NodeJS上構建一個承諾邏輯。我有一個API來跟蹤工作時間。使用PostgreSQL構建具有邏輯的承諾鏈
人們只需輸入他們的PIN碼即可進入時鐘輸入或輸出。
對於CLOCK-IN部分,API()的作用是檢查數據庫(使用pg-promise的PostgreSQL)以查找帶有PIN的僱員ID。如果PIN無效(未找到員工),請用錯誤消息拒絕承諾。然後它必須查找他們的「ClockStatus」來驗證它們是否已經IN或OUT。它可以用檢索員工ID的相同查詢來完成。如果已經在IN,用消息拒絕承諾。然後它必須查找員工的班次ID。之後,它將收集Shift信息以比較時間。 Finnaly,如果將在數據庫中插入一行,並收集上一步收集的信息。
在短:
New Promise
Get the Employee ID and Clock Status, and Shift ID
Then
If No Employee found then reject the promise
Then
If Clock Status is already in, reject the promise with a different message
Then
Gather informations for the shift
Then
Insert a new row in the WorkHour table using Employee info and Shift informations
我有我的路由器在這裏(使用ExpressJS)
router.post('/clockin', function(req, res) {
//Execute the API
time
.clockin(req.body.pin)
.then(function(time) { res.send(time)})
.catch(function(err) { res.status(500).send(err) });
});
我試圖建立的承諾鏈,但我不想被抓厄運的金字塔。
clockin: function(pin) {
// Getting the resourceID from PIN
var p = new Promise((resolve, reject) => {
if (pin === undefined) {
throw new Error('No PIN');
} else {
db.any('SELECT id, timeclockstatus From Employee Where PIN = $1', pin)
.then((EmployeeInfos) => {
return (db.any('select id, timeclockstatus from res_resources where id = $1 ', ResourceID[0].id))
})
//****** I'm stuck here
我想使用ES6的本地承諾。我試圖查找例子,但沒有一個看起來符合我的要求。或者,也許我錯過了什麼... 任何建議?
試試下面的僞代碼。請注意,如果db.any返回承諾,則不需要使用您在發佈的代碼中使用的Promise構造函數反模式 –
在轉換模式之前如何調用'clockin()'(或'clockout')是已知的? –
您的示例中的「ResourceID [0]」引用的內容並不清楚。 –