0

I am trying out json-rules-engine and I thought of making an extremely simple express api to try it out. But, it turns out it's giving me a tough time.

The array I am trying to return in the body is always an empty one, even if I do console.log in the map it actually logs the messages.

I have this controller:

'use strict';

var rulesEngine = require('./rulesEngine');

exports.run = function(req, res) {
  var outcome = rulesEngine.run(req.params.numberOfFaults);   
  res.json({outcome: outcome});
}

And the rulesEngine run method would be this one:

exports.run = function(numberOfFaults) {
  var facts = {
    personalFoulCount: numberOfFaults,
    gameDuration: 40
  },
  outcome = [];
  rulesEngine
    .run(facts)
    .then(events => { // run() returns events with truthy conditions 
      events.map(event => outcome.push(event.params.message))
  })
  return outcome;
};

Thanks!

2 Answers 2

1

You need to wait for the promise to complete before you return the outcome variable. Right now you're calling rulesEngine and return outcome right after, which in an asynchronous language like Javascript gets run immediately after one another.

Place the 'return outcome' inside the .then like so:

exports.run = function(numberOfFaults) {
  var facts = {
    personalFoulCount: numberOfFaults,
    gameDuration: 40
  },
  outcome = [];
  return rulesEngine
    .run(facts)
    .then(events => { // run() returns events with truthy conditions 
      events.map(event => outcome.push(event.params.message))

      return outcome;
  })
};
Sign up to request clarification or add additional context in comments.

Comments

0

You are dealing with rulesEngine.run() like it was synchronous, but it is asynchronous.

You gotta wait for it to finish in order to quit your run function.

For example :

      exports.run = function (req, res) {
          rulesEngine.run(req.params.numberOfFaults)
            .then((ret) => {
              res.json({
                outcome: ret,
              });
            })
            .catch((err) => {
              // Deal with error
            });
        }

     exports.run = function (numberOfFaults) {
      return new Promise((resolve, reject) => {
        const facts = {
          personalFoulCount: numberOfFaults,
          gameDuration: 40
        };

        rulesEngine
          .run(facts)
          .then(events => resolve(events.map(event => event.params.message)))
          .catch(reject);
      });
    }

1 Comment

Thanks! can't seem to map and resolve inside the then though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.