我是JS和Node的新手,我一直在尝试编写用于人员管理的API,例如跟踪员工的缺勤情况,并且我将Node与express.js结合使用。
当我决定将功能放在自己的模块/文件中时,我遇到了排序问题。
当经理在 localhost:3000 / user / $ userId 上执行GET请求时,我基本上想检索员工缺席的情况,但是我的功能运行不正常,我一直在阅读有关节点回调,但我仍然无法弄清楚。
API调用的代码:
/* 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}`);
});
用于检索员工及其缺勤情况的API函数的代码。
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}`);
}
乱序输出示例: