I'm new to JS and Node, i've been trying to write an API for people management like keeping track of employees absences and I'm using Node with express.js.
I currently ran into a problem of ordering when i decided to put the functions in their own module/file.
I basically want to retrieve a employee absences when a manager does a GET request on localhost:3000/user/$userId , but my functions are running out of order and i've been reading about node callbacks but i still couldn't figure it out.
Code of the API call:
/* Returns for each employee find her/his absences */
app.get('/user/:userId', async (req, res) => {
let employee = api.getEmployeeAbsences(req.params.userId);
console.log(`Employee retrivied ${employee}`);
});
Code of the API function that retrives the employee and his absences.
const readJsonFile = (path) => new Promise((resolve) => fs.readFile(path, 'utf8', (_, data) => resolve(data)))
.then((data) => JSON.parse(data))
.then((data) => data.payload);
export const members = () => readJsonFile(MEMBERS_PATH);
export const absences = () => readJsonFile(ABSENCES_PATH);
var exports = module.exports = {};
/* Returns the employee(given by the userId) info and his last absence if she or he exists */
exports.getEmployeeAbsences = function(userId) {
console.log('Start of Function');
members().then((employees) => {
console.log('Members');
let employee = employees.filter(emp => userId == emp.userId)[0];
// If employee wasn't found
if (!employee) {
return undefined;
} else {
absences().then((absences) => {
console.log('Absences');
// Assigning employee absences
employee = Object.assign(employee, { absences: absences.filter(abs => employee.userId == abs.userId) });
console.log(employee);
return employee;
});
}
});
console.log(`End of function ${userId}`);
}
Out of Order Output Example: