I'm new to node and promises. I have two files - server.js
and db.js
server.js
imports db.js
as modules.
I'm fetching some data from a SQL database in a db.js
module and I'm trying to pass that data to a function in server.js
.
I've successfully fetched the data from database, but when I try to pass it to the function in server.js
, it only returns an undefined
value.
Here's the code
server.js
const db = require('./db.js');
app.post('/api/trigger-push-msg/', function (req, res) {
return getSubscriptionsFromDatabase()
.then(function(subscriptions) {
// Do something
});
});
function getSubscriptionsFromDatabase() {
return new Promise((resolve, reject) => {
let subscriptions = db.getSubscriptions();
console.log(subscriptions); // this only prints "undefined"
if (subscriptions != undefined) {
resolve(subscriptions);
} else {
reject("No"); // this executes
}
})
}
db.js
module.exports = {
getSubscriptions: function() {
var sql = "SELECT * FROM subscriptions";
con.query(sql, function(err, result) {
if (err) throw err;
console.log(result); // this prints the same result as I want
return result;
})
}
}