First, pardon my slightly ambiguous title; I could not find a more appropriate one:
Scenario
I am using Mongoose to fetch some data and then render them with ejs. For the sake of illustration, consider the following:
// Schema
var UserSchema = mongoose.Schema({
Username: String,
City: String
})
// Model
var User = mongoose.model('User', UserSchema);
From my server file:
app.get('/view', function (req, res) {
// What I am trying to do
User.find({}).exec().then(vals=>{
res.send(vals)
})
The Problem
The above code works as intended but, to the code accessible to other files as well as making upgrades easier, I want to move it another file, then require() that file.
handler.js
// Promise: Get All Names
function FetchData(){
return User
.find({})
.exec();
}
module.exports = {
Get: function(){
val = User.find({}).exec()
.then(vals=>{
// Expected to return only after the above is complete
return vals
})
}
}
Then, from my server file:
var handler = require('handler')
app.get('/view', function (req, res) {
res.send(handler.Get())
});
Unfortunately, this code does not work as intended
My thoughts
I varied the parameters and tweaked the code around a few times but am unable to figure out what is going wrong. It seems that the values from Get() is being returned even before the promise is consumed (which is puzzling).
Any help would be greatly welcomed :)