0

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:

Out of order output

Community
  • 1
  • 1
murthaA
  • 371
  • 1
  • 4
  • 14
  • 1
    You need to `return` each `Promise` call. eg `return members().then(...` and `return absences()...` and call `.then` on the resulting `Promise` in the consumer (or use `await`) – CertainPerformance Oct 28 '18 at 00:46
  • @CertainPerformance thanks for the quick reply, I'm still a beginner with node and JS so i didn't exactly know what to search for and i didn't find that answer. – murthaA Oct 28 '18 at 01:38

0 Answers0