Reputation: 1484
After I execute a function (getAvailableLabs) in this case - I want to either execute a callback or a promise. I'm not sure which I should be executing however I can't get either to work.
Routes:
router.get('/api/content_left', function(req, res, next){
const Labs = require("../models/Labs.js");
l = new Labs("Sample Lab", "Sample Description", "Sample Category", "Sample Tech");
l.getAvailableLabs(function(){
console.log("We made it here!");
});
console.log("This is post resposnse");
Labs.js:
getAvailableLabs() {
var d = db.any('select * from labs')
.then(data => {
console.log(data[0]);
return data
})
.catch(function (error) {
console.log(error + " - Error in function");
return error;
});
}
In the above case, it logs "end of available labs" followed by "this is post response". That's what I would expect with my understanding of callbacks. However it never executes "We made it here!" and I don't understand why? My impression is if I place a function within a function - it will be executed as a callback however this does not happen. Do I need return a specific way to execute a callback?
Thank you for your help.
Upvotes: 1
Views: 1440
Reputation: 31761
Your getAvailableLabs
function does not accept a callback parameter. I think it'd be best to stay consistent and use promises:
getAvailableLabs() {
return db.any('select * from labs')
.then(data => {
console.log(data[0]);
return data
})
.catch(function (error) {
console.log(error + " - Error in function");
return error;
});
}
...
l.getAvailableLabs().then(data => {
console.log("We made it here!");
});
If you'd like to use a callback instead of a promise here's how I'd write getAvailableLabs
:
getAvailableLabs (callback) {
db.any('select * from labs')
.then(data => {
console.log(data[0]);
if (callback) { callback(null, data); }
})
.catch(function (error) {
console.log(error + " - Error in function");
if (callback) { callback(error); }
});
}
Calling this function:
getAvailableLabs((err, data) => console.log("We made it here!");
Upvotes: 5