Reputation: 5165
I've just started coding in NodeJS and I've got one question. I'm stuck in this place. I know that NodeJS is asyncronous but whenever i do a 'GET' for / I get a blank response.
/* GET home page. */
router.get('/', function(req, res, next) {
var tenantID = 1; //Hardcoded TODO: Remove this value later
var dwelltest = dwellTimeBucketModel.fetchFromDB(tenantID);
//I have a model in which I do all the DB calls (Cleaner to seperate?)
res.json({dwell: dwelltest}); //Send response back
}
Now, everytime I do this, my response gets sent out blank. (I know that this is due to async behavior). I am not sure how to get it working?
I've tried doing this:
var dwellResult = new Promise(function(resolve, reject){
dwellTimeBucketModel.fetchFromDB(tenantID);
});
dwellResult.then(function (result) {
console.log(result);
res.json({dwell: result})
}).catch(function (error) {
console.error(error);
})
But the response is never sent. I am not sure what i am doing wrong?
Please advise if i'm following the right practice? (or standard?)
Thanks
Upvotes: 0
Views: 86
Reputation: 4608
If you take a look at promise syntax here it is-
var p = new Promise(function(resolve, reject) {
// Do an async task async task and then...
if(/* good condition */) {
resolve('Success!');
}
else {
reject('Failure!');
}
});
p.then(function(response) {
/* do something with the result */
}).catch(function() {
/* error :( */
})
Here are two more detailed articles for studying.
Upvotes: 1
Reputation: 665
Add resolve to the promise
var dwellResult = new Promise(function(resolve, reject){
resolve(dwellTimeBucketModel.fetchFromDB(tenantID));
});
Upvotes: 3