I've written some JavaScript code:
app.get('/offers/', function(req, res){
var funcGetOffers = utils.funcGetOffers;
var options = {top_sort: true};
funcGetOffers(function(offers){
res.render('offers', { offers:offers });
}, options);
});
app.get('/api/get_offers', function(req, res){
var funcGetOffers = utils.funcGetOffers;
var options = {top_sort: true};
funcGetOffers(function(offers){
res.json(offers);
}, options);
});
The code is almost the same, and only the callback function is different. I want to get rid of the repeat code, but didn't find a good way.
funcGetOffers
is a long function which gets a list of items from the database:
var funcGetOffers = function(callback, opt) {
var order = [['updatedAt', 'DESC']];
var where = {};
if (opt && opt.top_sort) {
order.unshift(['flag_top', 'DESC']);
}
var Offer = models.offer;
Offer.findAll({order:order}).success(function(offers){
// some calc with offers
// callback
callback(offers);
});
}
Thank @Flambino make me more clear, I did some change to funcGetOffers
to make it promisily, now the code:
var options = {top_sort: true};
utils.funcGetOffers(options).then(function(offers){
res.render('offers', { offers:offers });
});
utils.funcGetOffers(options).then(function(offers){
res.json(offers);
});
changed the funcGetOffers
signature, use a bluebird to make it promisily.
utils.funcGetOffers(options).then(res.json)
didn't work by the promise, but looks much better now!