对象不从承诺函数返回

时间:2015-11-19 01:54:51

标签: node.js promise yeoman

// Thing is a mongoose model imported from thing.model.js file (the mongoose in that file has been promisify)    
exports.show = function(req, res) {
   return res.json(getThing(req.params.id))
};

function getThing(thingID){
  return Thing.findByIdAsync(thingID).then(function(thing){
     return thing;
  })
}

如何从功能中解决问题。现在,它只返回一个promise对象(解析和拒绝字段)。如果我删除getThing帮助函数中的第一个'return',它将不返回任何内容。 (我尝试了console.log(当时回调块中的东西,它工作正常))

如果我这样写:

exports.show = function(req, res) {
  return Thing.findByIdAsync(req.params.id)
              .then(function(thing){return res.json(thing);})
};

它会起作用!为什么呢?

1 个答案:

答案 0 :(得分:2)

这是您的顶级代码段

exports.show = function(req, res) {
   return res.json(getThing(req.params.id))
};

function getThing(thingID){
  return Thing.findByIdAsync(thingID).then(function(thing){
     return thing;
  })
}

getThing中.then是多余的,因此getThing基本上是

function getThing(thingID){
  return Thing.findByIdAsync(thingID);
}

所以exports.show基本上是

exports.show = function(req, res) {
   return res.json(Thing.findByIdAsync(req.params.id))
};

你实际上是在Promise上做一个res.json

与:

不同
exports.show = function(req, res) {
  return Thing.findByIdAsync(req.params.id)
    .then(function(thing){return res.json(thing);})
};

您要返回findByIdAsync

结果的res.json承诺

如果要拆分功能

,您想要做什么
exports.show = function(req, res) {
   return getThing(req.params.id)
    .then(function(thing){return res.json(thing);})
};

function getThing(thingID){
  return Thing.findByIdAsync(thingID);
}

exports.show = function(req, res) {
   return getThing(req.params.id);
};

function getThing(thingID){
  return Thing.findByIdAsync(thingID)
    .then(function(thing){return res.json(thing);});
}
相关问题