简体   繁体   中英

Bluebird promises no data received

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;

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM