0

I come from an object orientated background and the following would be my ideal syntax for combining the attributes of two or more models in a json response with Express:

//Verbose 
app.get('/boat_house', function(req, res){

  var boat = Model1;
  var house = Model2;

  var bColour = boat.colour;
  var hWidth = house.width;

  res.jsonp({
    boatColour: bColour,
    houseWidth: hWidth,
  });

});

//Compact
app.get('/boat_house', function(req, res){

  res.jsonp({
    boatColour: Model1.colour,
    houseWidth: Model2.width,
  });

});

From what I have seen, this is not possible. I have looked into fibers and async and I understand that Node is full of many modules to solve many problems. Though I have ended up chasing my tail while trying to emulate the above.

  1. How do I combine attributes from Model1 and Model2 into res.jsonp?
  2. What anti callback hell module best emulates the above syntax?
  3. Am I missing an epiphany? Do I need to let go of my OO ways and understand how to solve my problems (namely the one above) in a functional/modular manner?

EDIT:

The models are retrieved from a datastore. For example with the mongoose API you would retrieve Model1 by:

Boat.findOne(function(boat){
  //do something with boat
});

I have come across this similar question, the answer to which suggests the use of async.parallel. I would prefer a syntax similar to the following:

var when = require('HypotheticalPromiseModule').when;

var boat = Model1.getAsync();
var house = Model2.getAsync();

when(boat, house).then(function() {
   res.jsonp({ ... });
});

Is there an npm module out there that would give me this?

Community
  • 1
  • 1
waigani
  • 3,570
  • 5
  • 46
  • 71

1 Answers1

0

I might be misunderstanding, but:

var express = require('express');
var app = express();

var M1 = { colour: 'blue' };
var M2 = { width: 100 };

app.get('/test', function(req,res,next) {
  res.jsonp( { foo: M1.colour, bar: M2.width } );
});

app.listen(3003);

Testing it:

$ curl localhost:3003/test
{
  "foo": "blue",
  "bar": 100
}
$ curl localhost:3003/test?callback=func
typeof func === 'function' && func({
  "foo": "blue",
  "bar": 100
});

I think this is quite similar to your code, and I would say it works like expected.

My answers would then probably go something like:

  1. Just the way you think
  2. N/A
  3. Probably! That's normal, but you seem to be coping just fine. :)
Øystein Steimler
  • 1,579
  • 1
  • 11
  • 11
  • Ah, model1 and model2 are retrieved from a database. For example Boat.findOne(function(model1){ //do something with model }. I'll update my question. – waigani Oct 23 '13 at 03:20