我正在尝试json-rules-engine我虽然制作了一个非常简单的快速api来尝试它,但事实证明它给了我一个艰难的时间。
我试图在正文中返回的数组总是空的,即使我在地图中执行console.log实际记录消息
我有这个控制器:
'use strict';
var rulesEngine = require('./rulesEngine');
exports.run = function(req, res) {
var outcome = rulesEngine.run(req.params.numberOfFaults);
res.json({outcome: outcome});
}
ruleEngine run方法就是这个
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;
};
谢谢!
答案 0 :(得分:1)
在返回结果变量之前,您需要等待承诺完成。现在你正在调用rulesEngine并在之后返回结果,这在Javascript之类的异步语言中会立即运行。
放置'返回结果'在.then内部像这样:
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;
})
};
答案 1 :(得分:0)
您正在处理rulesEngine.run()
synchronous
,但它是asynchronous
。
您必须等待它完成才能退出run
功能。
例如:
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);
});
}