I'm new to promise and trying to build a logic with promises on NodeJS. I have an API for keep track of worked hours.
People just have to enter their PIN number to Clock In or Out.
What the API (for the CLOCK-IN part) does, is to check the database (PostgreSQL with pg-promise) to find the Employee ID with the PIN. If PIN is invalid (no employee has been found), reject the promise with an error message. Then it have to lookup for their "ClockStatus" to verify if they are already IN or OUT. It can be done with the same query that retrieve the Employee ID. If already IN, reject the promise with message. Then it have to lookup for the Shift ID from the Employee. After that, it will gather the Shift informations to compare Time. Finnaly, if will insert a row in the database with gathered informations from previous step.
In Short :
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
I have my router here (Using 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) });
});
I'm trying to build the promise chain, but I don't want to be caught in a pyramide of doom.
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
I would like to use native promise of ES6. I tried to lookup for examples but none seem to fit what i'm looking for. Or maybe I'm missing something... Any suggestion ?