Bluebird promises data not received

I am trying to integrate promises in the API of the application that I am developing. I get "No data" in Postman from the following route, while the comment 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;
+4
source share
1 answer

Promise.tryperforms synchronously the execution of your function. Any synchronous exceptions will be turned into rejections on the returned promise. Try to do this with the help new Promiseas shown 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);
});
+4
source

All Articles