0

Trying to integrate promises into my seneca modules.

Firstly, we have the server.js file which exposes a route:

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

var seneca = require('seneca')();
var act = Promise.promisify(seneca.act, {context: seneca});

var payroll = require ('./app/payroll');
seneca.use(payroll);

var router = express.Router();

router.route('/')
  .get(function(req, res) {

    act({role:'payroll', cmd:'generate-weekly-report-data', wc: 1489363200})
      .then(function (data) {
       res.json(data)
      })
      .catch(function (err) {
        res.send(err)
      });

  })
app.use('/payroll', router);

app.listen(3000);
console.log("Magic happens at port 3000");

And then we've got the payroll module (payroll.js) which contains the start of some accounting features:

module.exports = function(options) {
  var Promise = require('bluebird');
  var seneca = this;
  var act = Promise.promisify(seneca.act, {context: seneca});

  var payStructure = require ('../plugins/pay-structure');
  seneca.use(payStructure);

  seneca.add({role:'payroll', cmd:'generate-weekly-report-data'}, function (args, done) {
    act({role:'pay-structure', cmd:'get'})
      .then(function (pay_structure) {
        var referralPayRate = pay_structure.referralPayRate
        var stylistPayRate = pay_structure.stylistPayRate

        done( null, act({role:'transactions', cmd:'get_week', wc: args.wc, condense: true, totals: true }) )
      })
      .catch(function (err) {
        done(err)
      });
  });

}

Any help appreciated.

Jack Robson
  • 2,184
  • 4
  • 27
  • 50

1 Answers1

0

Why does it all make sense as soon as you make a post? -_-''

ANSWER:

Problem is that I am returning a promise through my done callback to a function that isn't expecting a promise, it just wants some JSON data.

Instead, I need to add an additional chain to get the result from the promise, and then pass the json through the done.

So NOT:

act({role:'pay-structure', cmd:'get'})
  .then(function (pay_structure) {
    var referralPayRate = pay_structure.referralPayRate
    var stylistPayRate = pay_structure.stylistPayRate

    done( null, act({role:'transactions', cmd:'get_week', wc: args.wc, condense: true, totals: true }) )
  })
  .catch(function (err) {
    done(err)
  });

But YES to:

act({role:'pay-structure', cmd:'get'})
  .then(function (result) {
    pay_structure = result

    return act({role:'transactions', cmd:'get_week', wc: args.wc, condense: true, totals: true })
  }).then(function( transactions ) {
    done(transactions)
  })
  .catch(function (err) {
    done(err)
  });
Jack Robson
  • 2,184
  • 4
  • 27
  • 50