Zhehao Victor Zhou
Zhehao Victor Zhou

Reputation: 203

Object Not Return From Promise Function

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

How Can I get the thing out of the function. Right now , it just returns an promise object (resolve and reject fields). If I remove the first 'return' in the getThing helper function, it will then returns nothing. (I tried console.log(thing in the then callback block and it works fine))

If I wrote in this way:

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

It will work! Why?

Upvotes: 0

Views: 550

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

Here's your top snippet

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

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

in getThing the .then is redundant, so getThing is essentially

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

so exports.show is basically

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

you are essentially doing a res.json on a Promise

which is different to:

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

where you are returning a promise of res.json of the result of findByIdAsync

What you want to do if you want to split the functions

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

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

or

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

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

Upvotes: 2

Related Questions