Reputation: 3288
I am trying to integrate promises into the API of the application I am developing. I receive "No data received" in Postman from the following route whereas the commented-out block works just fine.
import User from './models/User';
import express from 'express';
import Promise from 'bluebird';
const router = express.Router();
router.get("/", function(req, res, next){
Promise.try(function(){
User.find({}, function(err, users) {
return Promise.resolve(users);
});
}).then(function(result){
if (result instanceof Function) {
result(res);
} else {
return res.json(result);
}
}).catch(function(err){
next(err);
});
});
/*
router.get("/", function(req, res, next){
User.find({}, function(err, users) {
return res.json(users);
});
});
*/
module.exports = router;
Upvotes: 4
Views: 56
Reputation: 48366
Promise.try
is synchronously executing your function. Any synchronous exceptions will be turned into rejections on the returned promise. Please try to do it with new Promise
as below.
var p = new Promise(function (resolve, reject){
User.find({}, function(err, users) {
if (err)
reject(err);
else
resolve(users);
});
});
p.then(function(result){
return res.json(result);
}).catch(function(err){
next(err);
});
Upvotes: 4