Matt The Ninja
Matt The Ninja

Reputation: 2729

Multiple DB Calls Without Chaining code in Javascript/NodeJs

I've been playing with NodeJS and express for a little while but I can't seem to get around this one.

On the product page I want to display

1) The Product

2) Relation Products

I want to be able to reuse this code and ideally I would be written something like this

/* Function to get info */

function getProduct($id){
    //Finds the product info from postgres with all information and returns it.
}

function getRelatedProducts($id){
    //Finds related products from postgres and returns it.
}   

/* Routing */
router.get('/:id', function(req, res, next) {
  var product = getProduct(req.params.id);
  var relatedProducts = getRelatedProducts(req.params.id);
  res.render('product', { item: product, related: relatedProducts });
});

As you'd expect this doesn't work as the code hits res.render before it has time to return product & relatedProducts.

Now I have a few way to achieve getting around this but I wanted to know what the best pattern/way of achieving this is. So that I dont then have to reproduce code.

If some of the above doesn't make sense please let me know! Many thanks in advance (from the JS newbie!)

Upvotes: 1

Views: 65

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

The best pattern is arguable, but one solution would be to use promises. In each of the functions that gets products/related products by ID you would return a promise that is resolved when the query is complete. Then, when both of those promises are resolved, you render.

var productPromise = getProduct(req.params.id);
var relatedProductsPromise = getRelatedProducts(req.params.id);
Promise.all([productPromise, relatedProductsPromise]).then(
  function (product, relatedProducts) {
    res.render('product', { item: product, related: relatedProducts });
  }
);

Upvotes: 3

Related Questions