I have a problem about executing a callback function. I just created an helper function to be used for by router and internal purposes. Helper function is working perfectly for the router part (tried with postman) but when I try to execute helper function alone, problems arise.
const MyModel= require('../model/MyModel');
const ERR_REASON = {
SERVER: 'SERVER_FAULT',
DB: 'DB_FAULT',
};
const getCommunicationDiagnosticsHelper =function (start, end, cbf) {
/*
If I execute my callback function here, it works
*/
MyModel.aggregate([
//aggregator operators are passed here,
//I'm not providing the pipeline operators list but they work fine!
])
.allowDiskUse(true)
.exec(function (err, results) {
// START-This part of code is never executed in my function
if (err) {
cbf(true,ERR_REASON.DB,null)
}
try {
cbf(false,null,results)
} catch (error) {
cbf(true,ERR_REASON.SERVER,null)
}
// END-This part of code is never executed in my function
});
};
This works fine,
function cb(err,info,data){
console.log({err,info,data})
//supposed everything went well
//this refers to `res`
this.status(200).json(data)
}
const getCommunicationDiagnostics = function (req, res, next) {
// start and end variables are to be used in aggregation.
// parseDate is a simple utility function,
const { start, end } = parseDate(req.params.interval);
getCommunicationDiagnosticsHelper(start, end, cb.bind(res))
};
//router.js
const router=require('express').Router();
router.get('/com_diagnostics',getCommunicationDiagnostics)
But this doesn't. I expect the callback function (as argument) to execute, but it is not executing.
getCommunicationDiagnosticsHelper('2021-01-19T19:59:59.999Z','2021-01-20T19:59:59.999Z',(err, info, data) => {
//This part of code is never reached!
console.log({err,info,data});
})
Why does the helper function complete execution even though the callback function is not executed?